103

I'm trying to make a font in a div responsive to the browser window. So far, it has worked perfectly, but the parent div has a max-width of 525px. Resizing the browser further will not make the font stop resizing. This has made me wonder if there is such a thing as min-font-size or max-font-size, and if such a thing does not exist, if there is a way to achieve something similar.

I thought that using percentages at font-size would work, but the bit of text won't scale accordingly to the parent div. Here's what I have:

The CSS for the parent div:

.textField{
    background-color:rgba(88, 88, 88, 0.33);

    width:40%;
    height:450px;

    min-width:200px;
    max-width:525px;

    z-index:2;
}

The CSS for the piece of text in question:

.subText{
    position:relative;
    top:-55px;
    left:15px;

    font-family:"news_gothic";
    font-size:1.3vw;
    font-size-adjust:auto;

    width:90%;

    color:white;

    z-index:1;
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Toby van Kempen
  • 1,447
  • 4
  • 13
  • 20

12 Answers12

126

You can do it by using a formula and including the viewport width.

font-size: calc(7px + .5vw);

This sets the minimum font size at 7px and amplifies it by .5vw depending on the viewport width.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Brad Ahrens
  • 4,864
  • 5
  • 36
  • 47
  • 3
    OMG!!! for the last 3 days I've been playing with numbers and different ways of doing this. Let me tell you nothing really worked like want it to. Then, I come across your answer, plugged in your answer into my css and "HORAYYYY" it works... Awesome answer Pitt. Thanks. – ThN Jun 21 '17 at 13:21
  • A great trick for minimum font-size. I wonder if something similar can be done for maximum... Could have something to do with the idea that any negative would be treated as `0`. Some nested `calc`s or something? – Lazar Ljubenović Aug 12 '17 at 09:14
  • 2
    Invert it, so font-size: calc(12px - .5vw) – roberrrt-s Dec 07 '17 at 12:47
  • This does not work properly with LESS. I guess the `calc()` statement is processed when the LESS is compiled and resolves to a simple `px` value. Resizing does not recalculate. Ideas or thoughts? –  Mar 26 '18 at 21:11
  • Posted here: https://stackoverflow.com/questions/49500754/using-css-calc-at-runtime-with-less-precompiler –  Mar 26 '18 at 21:17
  • This does not seem like a valid general purpose solution. In one case I tested, I need a font size of 44px or 5vh, whichever is greater. But it is adding the two,often resulting in twice the required size ! – Michael Jun 25 '18 at 21:05
  • @Michael You can achieve that using media queries. Work out by hand where the transition is (here it's at 44px = 5vh, so viewport height of 880px) then set up your media query for 44px font when viewport < 880px, .5vh otherwise. – GKFX Jan 05 '19 at 21:34
63

It works well with CSS.

I went through the same issues and fixed it as follow.

Use a fixed "px" size for maximum size at a specific width and above. Then for different smaller widths, use a relative "vw" as a percentage of the screen.

The result below is that it adjusts itself at screens below 960px but keep a fixed size above. Just a reminder, not to forget to add in the html doc in header:

<meta name="viewport" content="width=device-width">

Example in CSS:

@media all and (min-width: 960px) {
h1{
    font-size: 50px;
  }
}

@media all and (max-width: 959px) and (min-width: 600px) {
h1{
    font-size: 5vw;
  }
}

@media all and (max-width: 599px) and (min-width: 50px) {
h1{
    font-size: 6vw;
  }
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Willy VAN INGEN
  • 631
  • 5
  • 2
  • 2
    This should be the BEST answer!! – KaKa Feb 03 '17 at 08:10
  • why do you have 'all' in each row? – tibi Jul 04 '18 at 12:59
  • @tibi all refers to the media type (or: WHERE to apply). options are all, screen, print & speech. all is default, so its kinda obsolete here. see [mdn](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) docs. – honk31 Dec 11 '19 at 13:27
  • Yes! This works perfectly! What I wanted was a MAX font size, and this works perfectly, thank you. – todbott Jun 17 '20 at 23:34
61

No, there is no CSS property for minimum or maximum font size. Browsers often have a setting for minimum font size, but that’s under the control of the user, not an author.

You can use @media queries to make some CSS settings depending on things like screen or window width. In such settings, you can e.g. set the font size to a specific small value if the window is very narrow.

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390
  • If I'm correct, the information in your link says that media queries will execute the specified CSS when a condition has been met, in this case of your link, the condition would be `max-width:600px;`. Am I correct or did I not correctly understand the information behind the link? – Toby van Kempen May 09 '14 at 08:57
  • 4
    @Toby van Kempen: You are correct, however the max-width in this case refers to the screen viewport size, and not the size of an arbitrary element. If you need to change CSS depending on the style of some arbitrary element, then you won't be able to use media queries to do so. You'll need a script. – BoltClock May 09 '14 at 09:08
  • @BoltClock So, `@media` refers to the browser window? How will it know that I want my font size to be, say, 20px when the parent div or browser window is of a specific size, in px? – Toby van Kempen May 09 '14 at 09:46
  • @Toby van Kempen: It will *always* refer to the browser window - hence the "media" in "media queries". – BoltClock May 09 '14 at 09:47
  • 1
    Ah, I see. So, if I'm correct, if I write `@media (width:600px)`, it will run the script below `@media` once the browser width is equivalent to 600px? – Toby van Kempen May 09 '14 at 09:49
  • @BoltClock Thank you for your confirmation and explanation about these media queries. – Toby van Kempen May 09 '14 at 10:05
  • +1. the need of the OP is perfectly met using media queries on window width/height. In his scenario he will achieve exactly the same result as setting a max-font-size. Anyway, I can still think at other use cases where the property would still be handy. – Francesco Frapporti Sep 26 '14 at 15:05
  • @Jukka K. Korpela, will you update your answer to include the min(), max(), and clamp() functions? This question is highly ranked in searches, therefore providing complete, up-to-date information is important. – Foo Bar May 21 '20 at 16:31
10

I am coming a bit late here, I don't get that much credit for it, I am just doing a mix of the answers below because I was forced to do that for a project.

So to answer the question : There is no such thing as this CSS property. I don't know why, but I think it's because they are afraid of a misused of this property, but I don't find any use case where it can be a serious problem.

Whatever, what are the solutions ?

Two tools will allow us to do that : media queries ans vw property

1) There is a "fool" solution consisting in making a media query for every step we eant in our css, changing font from a fixed amount to another fixed amount. It works, but it is very boring to do, and you don't have a smooth linear aspect.

2) As AlmostPitt explained, there is a brillant solution for the minima :

font-size: calc(7px + .5vw);

Minimum here would be 7px in addition to 0.5% of the view width. That is already really cool and working in most of cases. It does not require any media query, you just have to spend some time finding the right parameters.

As you noticed it is a linear function, basic maths learn you that two points already find you the parameters. Then just fix the font-size in px you want for very large screens and for mobile version, then calculate if you want to do a scientific method. Thought, it is absolutely not necessary and you can just go by trying.

3) Let's suppose you have a very boring client (like me) who absolutely wants a title to be one line and no more. If you used AlmostPitt solution, then you are in trouble because your font will keep growing, and if you have a fixed width container (like bootstrap stoping at 1140px or something in large windows). Here I suggest you to use also a media query. In fact you can just find the amout of px size maximum you can handle in your container before the aspect become unwanted (pxMax). This will be your maximum. Then you just have to find the exact screen width you must stop (wMax). (I let you inverse a linear function on your own).

After that just do

@media (min-width: [wMax]px) {
    h2{
        font-size: [pxMax]px;
    }
}

Then it is perfectly linear and your font-size stop growing ! Notice that you don't need to put your previous css property (calc...) in a media query under wMax because media query are considered as more imnportant and it will overwrite the previous property.

I don't think it is useful to make a snippet for this, as you would have trouble to make it to whole screen and it is not rocket science afterall.

Hope this could help others, and don't forget to thank AlmostPitt for his solution.

hol
  • 8,255
  • 5
  • 33
  • 59
Alburkerk
  • 1,564
  • 13
  • 19
  • Can you suggest a formula for finding the right values for calc() which return the same as `max(*a*px,, *b*vw)`? Because in my case, I can't tolerate a naive addition because the result is too large, but it sounds like you are suggesting I could somehow reduce a and b over the naive amounts - I am having trouble figuring the math out, and I need a general solution, not just a specific case. – Michael Jun 25 '18 at 21:12
  • Only good explanation I came up with was with an image, so I can't help you via comments, I suggest you create a new question – Alburkerk Jun 26 '18 at 11:55
6

This is actually being proposed in CSS4

Working draft at the W3C

Quote:

These two properties allow a website or user to require an element’s font size to be clamped within the range supplied with these two properties. If the computed value font-size is outside the bounds created by font-min-size and font-max-size, the use value of font-size is clamped to the values specified in these two properties.

This would actually work as following:

.element {
    font-min-size: 10px;
    font-max-size: 18px;
    font-size: 5vw; // viewport-relative units are responsive.
}

This would literally mean, the font size will be 5% of the viewport's width, but never smaller than 10 pixels, and never larger than 18 pixels.

Unfortunately, this feature isn't implemented anywhere yet, (not even on caniuse.com).

roberrrt-s
  • 7,914
  • 2
  • 46
  • 57
  • 4
    Great. So I just have to stop working on this project for a few years until this gets implemented.... :'-( – Michael Jun 25 '18 at 21:09
6

CSS min() and max() have fairly good usage rates in 2020.

The code below uses max() to get the largest of the [variablevalue] and [minimumvalue] and then passes that through to min() against the [maximumvalue] to get the smaller of the two. This creates an allowable font range (3.5rem is minimum, 6.5rem is maximum, 6vw is used only when in between).

font-size: min(max([variablevalue], [minimumvalue]), [maximumvalue]);
font-size: min(max(6vw, 3.5rem), 6.5rem);

I'm using this specifically with font-awesome as a video-play icon over an image within a bootstrap container element where max-width is set.

franklylately
  • 1,112
  • 10
  • 12
  • Fiiinally. Thank you for explaining what each of the numbers do better than the blog post I found on Google with the same formula. I was literally giving up when I was scrolling to the bottom of the page to find your answer. And thank goodness I don't have to add in all those ridiculous SASS variables and `@media` nonsense and whatever else – velkoon May 21 '21 at 17:38
  • You can also write `font-size: clamp(16px, 1.4vw, 22px)` instead of using `min()` and `max()`, where 16px is the minimum, and 22px is the maximum. – mph Jan 21 '23 at 20:58
3

Rucksack is brilliant, but you don't necessarily have to resort to build tools like Gulp or Grunt etc.

I made a demo using CSS Custom Properties (CSS Variables) to easily control the min and max font sizes.

Like so:

* {
  /* Calculation */
  --diff: calc(var(--max-size) - var(--min-size));
  --responsive: calc((var(--min-size) * 1px) + var(--diff) * ((100vw - 420px) / (1200 - 420))); /* Ranges from 421px to 1199px */
}

h1 {
  --max-size: 50;
  --min-size: 25;
  font-size: var(--responsive);
}

h2 {
  --max-size: 40;
  --min-size: 20;
  font-size: var(--responsive);
}
Dannie Vinther
  • 183
  • 1
  • 5
2

I got some smooth results with these. It flows smoothly between the 3 width ranges, like a continuous piecewise function.

@media screen and (min-width: 581px) and (max-width: 1760px){
    #expandingHeader {
        line-height:5.2vw;
        font-size: 5.99vw;
    }
    #tagLine {
        letter-spacing: .15vw;
        font-size: 1.7vw;
        line-height:1.0vw;
    }
}

@media screen and (min-width: 1761px){
    #expandingHeader {
        line-height:.9em;
        font-size: 7.03em;

    }
    #tagLine {
        letter-spacing: .15vw;
        font-size: 1.7vw;
        line-height:1.0vw;
    }
}

@media screen and (max-width: 580px){
    #expandingHeader {
        line-height:.9em;
        font-size: 2.3em;
    }
    #tagLine {
        letter-spacing: .1em;
        font-size: .65em;
        line-height: .10em;
    }
}
2

You can use Sass to control min and max font sizes. Here is a brilliant solution by Eduardo Boucas.

https://eduardoboucas.com/blog/2015/06/18/viewport-sized-typography-with-minimum-and-maximum-sizes.html

@mixin responsive-font($responsive, $min, $max: false, $fallback: false) {
  $responsive-unitless: $responsive / ($responsive - $responsive + 1);
  $dimension: if(unit($responsive) == 'vh', 'height', 'width');
  $min-breakpoint: $min / $responsive-unitless * 100;

  @media (max-#{$dimension}: #{$min-breakpoint}) {
    font-size: $min;
  }

  @if $max {
    $max-breakpoint: $max / $responsive-unitless * 100;

    @media (min-#{$dimension}: #{$max-breakpoint}) {
      font-size: $max;
    }
  }

  @if $fallback {
    font-size: $fallback;
  }

  font-size: $responsive;
}

.limit-min {
  @include responsive-font(3vw, 20px);
}

.limit-min-max {
  @include responsive-font(3vw, 20px, 50px);
}
Matt
  • 1,388
  • 15
  • 16
1

Please note that setting font-sizing with px is not recommended due to accessibility concerns:

"defining font sizes in px is not accessible, because the user cannot change the font size in some browsers. For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer." (see https://developer.mozilla.org/en-US/docs/Web/CSS/font-size)

A more accessible approach is to set font-size: 100% in the html, which respects user default size settings, and THEN using either percentages or relative units when resizing (em or rem), for example with a @media query.

(see https://betterwebtype.com/articles/2019/06/16/5-keys-to-accessible-web-typography/)

0

Yes, there seems some restrictions by some browser in SVG. The developertool restrict it to 8000px; The following dynamically generated Chart fails for example in Chrome.

Try http://www.xn--dddelei-n2a.de/2018/test-von-svt/

<svg id="diagrammChart"
     width="100%"
     height="100%"
     viewBox="-400000 0 1000000 550000"
     font-size="27559"
     overflow="hidden"
     preserveAspectRatio="xMidYMid meet"
>
    <g class="hover-check">
        <text class="hover-toggle" x="-16800" y="36857.506818182" opacity="1" height="24390.997159091" width="953959" font-size="27559">
            <set attributeName="opacity" to="1" begin="ExampShow56TestBarRect1.touchstart"
                 end="ExampShow56TestBarRect1.touchend">
            </set>
            <set attributeName="opacity" to="1" begin="ExampShow56TestBarRect1.mouseover"
                 end="ExampShow56TestBarRect1.mouseout">
            </set>
            Heinz: -16800
        </text>
        <rect class="hover-rect" x="-16800" y="12466.509659091" width="16800" height="24390.997159091" fill="darkred">
            <set attributeName="opacity" to="0.1" begin="ExampShow56TestBarRect1.mouseover"
                 end="ExampShow56TestBarRect1.mouseout">
            </set>
            <set attributeName="opacity" to="0.1" begin="ExampShow56TestBarRect1.touchstart"
                 end="ExampShow56TestBarRect1.touchend">
            </set>
        </rect>
        <rect id="ExampShow56TestBarRect1" x="-384261" y="0" width="953959" height="48781.994318182"
              opacity="0">
        </rect>

    </g>
</svg>
Padina
  • 1
0
font-size: min(max(0.7rem, 3vw), 2rem);

simple entry of the minimum - responsive - maximum value. The support in 2021 is almost 98%.