0

我有一个 4x4 Grid 组件,用于渲染 Tile 组件。Tile 组件呈现不同长度的数字(从 1 到 4 位)。

我希望调整字体大小以匹配容器的大小,而无需调整 Tile 组件的大小。我不想以任何方式更改 Tile 组件的位置/大小,只是为了使包含的文本的大小与 Tile 的大小相匹配。对字体大小的任何调整都会调整 Tile div 的大小,这非常令人沮丧。

https://codesandbox.io/s/agitated-kepler-fhjxm?file=/src/App.js

import React from "react";
import styled from "styled-components";

const Grid = styled.div`
  width: 250px;
  height: 250px;
  background-color: pink;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(4, 1fr);
`;

const Tile = styled.div`
  margin: 1.5vh 1vw;
  background-color: white;
  max-width: 100%;
  max-height: 100%;
  text-align: center;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  > p {
    font-size: 3vw;
  }
`;
const elements = [...Array(4)].map(() => [...Array(4)]);

export default function App() {
  return (
    <div className="App">
      <Grid>
        {elements.map(row =>
          row.map(e => (
            <Tile>
              <p>{0}</p>
            </Tile>
          ))
        )}
      </Grid>
    </div>
  );
}
4

1 回答 1

1

这是你想要的吗?现场演示

const Tile = styled.div`
  margin: 1.5vh 1vw;
  background-color: white;
  max-width: 100%;
  max-height: 100%;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  > span {
    font-size: 3vw;
    display: inline-block;
    vertical-align: middle;
    line-height: normal;
  }
`;
const elements = [...Array(4)].map(() => [...Array(4)]);

export default function App() {
  return (
    <div className="App">
      <Grid>
        {elements.map(row =>
          row.map(e => (
            <Tile>
              <span>{9999}</span>
            </Tile>
          ))
        )}
      </Grid>
    </div>
  );
}
于 2020-07-30T05:21:37.130 回答