Text that fills the width of a container

Hello, I am trying to write some SCSS to control the size of some text. The text needs to fill the width of the container but maintain the correct proportions on different viewports. I thought I might be able to achieve this with a container query. Currently I have…
.container {
container-type: inline-size;

h1 {
white-space: nowrap;
font-size: 7.75cqi;
}
}
.container {
container-type: inline-size;

h1 {
white-space: nowrap;
font-size: 7.75cqi;
}
}
This kind of works, in that if the text length doesn't change, it does scale. The problem comes with dynamic text, if there are more charters as an example, then the h1 will overflow the container. Thanks in advance
3 Replies
Choo♚𝕂𝕚𝕟𝕘
Specifying the font size based on a container query requires magic numbers and won't work with font substitution, because the font size is a height specification and not a width. Unless it's a fixed width font, getting the ratio of width to height for some math will still only give you an approximation, and it will fail completely if there is font substitution. The only non-JS solution I have seen makes creative use of the new scroll linked animation capabilities of CSS. This solution is not only very convoluted and non-intuitive, but it also doesn't have sufficient browser support yet to be good for use in production.
Choo♚𝕂𝕚𝕟𝕘
Fit-to-Width Text
What if I will tell you how we could solve fit-to-width text with pure CSS without any hardcoded parameters? Curiously, scroll-driven animations will allow us to do just that! Join me as I continue exploring the experimental implementations of the latest specs.
I am Groot
I am Groot2w ago
It might be able to be done with a calc() :root { --_font-size: calc((80vw / 80ch) * (100vw) / 80ch)) ; these calculation are not accurate and will need some magic numbering. but this might be a more usable solution across browsers
Want results from more Discord servers?
Add your server