Css – Pure CSS to make font-size responsive based on dynamic amount of characters

css

I know that this could be solved fairly easily with Javascript, but I'm only interested in a pure CSS solution.

I want a way to dynamically resize text so that it always fits into a fixed div. Here is the sample markup:

<div style="width: 200px; height: 1em; overflow: hidden;">
  <p>Some sample dynamic amount of text here</p>
</div>

I was thinking that maybe this could be possible by specifying the width of the container in ems, and getting the font-size to inherit that value?

Best Answer

Note: This solution changes based on viewport size and not the amount of content

I just found out that this is possible using VW units. They're the units associated with setting the viewport width. There are some drawbacks, such as lack of legacy browser support, but this is definitely something to seriously consider using. Plus you can still provide fallbacks for older browsers like so:

p {
    font-size: 30px;
    font-size: 3.5vw;
}

http://css-tricks.com/viewport-sized-typography/ and https://medium.com/design-ux/66bddb327bb1

Related Topic