cssresponsive-designfont-sizecss-variables

Can I combine minmax() with responsive length property in CSS?


I had the idea to use responsive font-size in CSS, so that the font size would depend on the viewport width, but be limited for minimum and maximum size, like this:

@property --font-size-norm {            /* normal */
    syntax: "<length>";
    inherits: true;
    initial-value: minmax(10pt, minmax(1.8vw, 14pt));
}

but the browser did not like it.

So I tried to set it to 10pt instead and add the rule

p {
    font-size: var(--font-size);
}

to a test element and at an outer element I set

.outer {
    --font-size: minmax(10pt,minmax(1.8vw, 14pt);
}

When resizing the viewport, the font size changes, but it gets larger than 14pt (and smaller than 10pt).

@property --font-size-norm {            /* normal */
    syntax: "<length>";
    inherits: true;
    initial-value: 1.8vw;
}

.outer {
  --font-size: minmax(10pt, minmax(1.8vw, 14pt));
}

.outer p {
  font-size: var(--font-size);
}
<html>
<body>
<div class="outer">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum</p>
</div>
</body>
</html>

In principle I would like to have the magic of sizing in the properties initial value, but I'm unsure whether that expression would be evaluated when the property is being defined, or each time when it is being used.


Solution

  • minmax() is not a valid CSS function for property values like font-size! It’s only used in CSS Grid to define track sizing, not for values like font-size, width, etc. Refer this

    clamp() is what you want. Use clamp(min, preferred, max). This lets you set a minimum, a scaling value, and a maximum and it works with font-size as well.

    .outer {
      --font-size: clamp(10pt, 1.8vw, 14pt);
    }
    
    .outer p {
      font-size: var(--font-size);
    }