How to make font-size relative to parent div?

Tachi picture Tachi · Jun 7, 2015 · Viewed 78.6k times · Source

I want text inside my div to remain same size in % percentage ratio to a parent div. I.E. I want my text to have font-size of 50% of parents div width. So when page size is changing, text always remains the same size in %.

Here Is what I'm talking about:

Run this snippet in full screen and try resizing the page and see how text size is changing and not fitting inside the div borders. How can I prevent it from happening, so it always remains inside the borders?

Answer

JamieR picture JamieR · Oct 23, 2017

The way I solved this problem was to use javascript to measure the container and then set the font size in px on that container. Once that baseline is set for the container then the relative font sizing of all the content will scale correctly using em or %.

I'm using React:

<div style={{ fontSize: width / 12 }} >
  ...
</div>

CSS:

div {
  font-size: 2em;
}