1

There is a similar question Is it possible to adapt font size to div width with CSS? which has a misleading title because it turns out in their example their div size depends on the viewport size, so their solution is to simply make font size dependent on the viewport size, too. However, my div size is in px and might change at any time. How do I adjust it's font size accordingly by using CSS only?

Values for font size in % unfortunately correspond to the parent font size, not to the parent container size.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example</title>
</head>
<style>
html, body {
  margin: 0;
  padding: 0;
  background-color: red;
}
div#content {
  margin: 0;
  padding: 0;
  background-color: blue;
  width: 100px; /* this might change at any time */
  font-size: 200%;
}
</style>
<body>
<div id="content">Text</div>
</body>
</html>
finefoot
  • 9,914
  • 7
  • 59
  • 102
  • To clarify a litle bit: I just want it to depend on the div size. I can fiddle with the values to get the size I want. My main issue: I want the font to scale accordingly when the div gets resized. – finefoot Apr 01 '22 at 20:10
  • You might be looking for a container query. See this [MDN page](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Container_Queries), this [blog post](https://ishadeed.com/article/say-hello-to-css-container-queries/), and this [Smashing Magazine article](https://www.smashingmagazine.com/2021/05/complete-guide-css-container-queries/) for more info. – Bumhan Yu Apr 01 '22 at 20:25
  • Unfortunately, it's support is pretty poor according to [caniuse](https://caniuse.com/css-container-queries), although it can be turned on in Chrome Canary and [its proposal](https://css.oddbird.net/rwd/query/explainer/) is in a sound shape. – Bumhan Yu Apr 01 '22 at 20:26
  • In the meantime, you could try a CSS variable and dynamically change its value with JavaScript. – Bumhan Yu Apr 01 '22 at 20:27
  • You might find your answer in this post here: https://stackoverflow.com/questions/16056591/font-scaling-based-on-width-of-container – Jorge Monte Apr 01 '22 at 21:02
  • @JorgeMonte Am I overlooking something? The only solution that doesn't use JS or viewport seems to be via SVG and that seems... unnecessarily complicated? :( – finefoot Apr 01 '22 at 21:38

0 Answers0