Pure CSS to make font-size responsive based on dynamic amount of characters
The only way would probably be to set different widths for different screen sizes, but this approach is pretty inacurate and you should use a js solution.
h1 {
font-size: 20px;
}
@media all and (max-device-width: 720px){
h1 {
font-size: 18px;
}
}
@media all and (max-device-width: 640px){
h1 {
font-size: 16px;
}
}
@media all and (max-device-width: 320px){
h1 {
font-size: 12px;
}
}
Edit: Watch out for attr() Its related to calc() in css. You may be able to achieve it in future.
Unfortunately for now there isn't a css only solution. This is what I suggest you do. To your element give a title attribute. And use text-overflow ellipsis to prevent breakage of the design and let user know more text is there.
<div style="width: 200px; height: 1em; text-overflow: ellipsis;" title="Some sample dynamic amount of text here">
Some sample dynamic amount of text here
</div>
.
.
.
Alternatively, If you just want to reduce size based on the viewport. CSS3 supports new dimensions that are relative to view port.
body {
font-size: 3.2vw;
}
- 3.2vw = 3.2% of width of viewport
- 3.2vh = 3.2% of height of viewport
- 3.2vmin = Smaller of 3.2vw or 3.2vh
- 3.2vmax = Bigger of 3.2vw or 3.2vh see css-tricks.com/.... and also look at caniuse.com/....
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
You might be interested in the calc
approach:
font-size: calc(4vw + 4vh + 2vmin);
done. Tweak values till matches your taste.
Source: https://codepen.io/CrocoDillon/pen/fBJxu