Perplexityy
Perplexityy

Reputation: 569

Make text size match container, without resizing it

I have a 4x4 Grid component, rendering Tile components. The Tile components render numbers of varying lengths (from 1 to 4 digits).

I want the font size to be adjusted to match the size of the container, without resizing the Tile components. I do not want to change the positions/sizes of the Tile components in any way, simply to make the size of the contained text match the size of the Tile. Any adjustments to the font size resize the Tile divs and its super frustrating.

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>
  );
}

Upvotes: 0

Views: 65

Answers (1)

Eric
Eric

Reputation: 1347

Is this what you want? live demo

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>
  );
}

Upvotes: 1

Related Questions