Home > front end >  How to make the font size to be responsive to it's parent's div's height? Not the win
How to make the font size to be responsive to it's parent's div's height? Not the win

Time:06-22

I'm a beginner developer and working on a simple word game. The play area size is fixed to the user device's screen size, and it is all defined at load. For the list of user input words I use grid and it fills the container with new rows as user adds more words to it. As the parent's container's height is fixed, when there's more words than the container can fit, for now I used overflow : scroll; but it would be better if all words were visible at all times.

<div >
  <div >
    <p >seahorse</p>
  </div>
  <div >
    <p >slimfit</p>
  </div>
  <div >
    <p >dlowjod</p>
  </div>
  <div >
    <p >blowtorch</p>
  </div>
</div>

so I have successfully made the .user-word-container to fill the .user-word-list dynamically changing their heights with grid-template-rows: (auto 1fr); but I just can't make the text inside of them shrink accordingly. I suspect that it's possible through javascript but I don't have enough knowledge to execute it and googling didn't bring any results. Thanks and peace!

CodePudding user response:

Try setting the parent font size to 2vh then specifying a em size for the child. the em keeps it relative to its parents font size which is set based on its height. Example:

<div style='font-size: 2vw;'>
  <div style='font-size: 4em;'>
    TEst
  </div>
</div>

CodePudding user response:

Thank you everyone who was here to help! I figured out my own original solution, here it is.

1.Getting the parent element: const userWords = document.querySelector('.user-word-list');

2.bringing it to an array and iterating over it every time a new word gets added like so:

Array.from(userWords.children).forEach(w => {

const boxHeight = w.offsetHeight;

const heightString = boxHeight.toString();

w.style.fontSize = ``${heightString}`` 'px';});

the result - it listens to my shrinking divs heights and changes font accordingly. The only thing it kinda cascades them from bigger word to smaller one, until there's not enough space for that and then they are all at minimum height, but I kinda like how it looks. Please, let me know if you know why it happens!

CodePudding user response:

Try using rem. For example: font-size: 40rem;

  • Related