Best Unit for Font-Sizes in CSS

Best unit for font-sizes in CSS

I would recommend EM — simply because I use Baseline CSS for my basic set up of forms, layout and most importantly type.

Can't recommend it enough : http://baselinecss.com/

Responsive font size in CSS

The font-size won't respond like this when resizing the browser window. Instead they respond to the browser zoom/type size settings, such as if you press Ctrl and + together on the keyboard while in the browser.

Media Queries

You would have to look at using media queries to reduce the font-size at certain intervals where it starts breaking your design and creating scrollbars.

For example, try adding this inside your CSS at the bottom, changing the 320 pixels width for wherever your design starts breaking:

@media only screen and (max-width: 320px) {

body {
font-size: 2em;
}

}

Viewport percentage lengths

You can also use viewport percentage lengths such as vw, vh, vmin and vmax. The official W3C document for this states:

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

Again, from the same W3C document each individual unit can be defined as below:

vw unit - Equal to 1% of the width of the initial containing block.

vh unit - Equal to 1% of the height of the initial containing block.

vmin unit - Equal to the smaller of vw or vh.

vmax unit - Equal to the larger of vw or vh.

And they are used in exactly the same way as any other CSS value:

.text {
font-size: 3vw;
}

.other-text {
font-size: 5vh;
}

Compatibility is relatively good as can be seen here. However, some versions of Internet Explorer and Edge don’t support vmax. Also, iOS 6 and 7 have an issue with the vh unit, which was fixed in iOS 8.

Unit for sizes in CSS

TL;DR:

  • Use % for horizontal page layout
  • em works great for vertical spacing
  • Use anything you prefer for font-size (I like em)
  • Use em for media queries

CSS Measurement Units

I find that my usage of different CSS measurement units varies with the area of measurement I'm dealing with: horizontal, vertical, typography, or media query.

Horizontal measurements

The horizontal space gives structure to the page. Thus, horizontal measurements work well with units relative to the page width (%). For example, it's great for giving some basic breathing room to the main content:

#main {
width: 90%;
margin: 0 auto;
}

More complex layouts (columns, for example) also work well when one or all of the horizontal measurements are proportional to the page or to their container.

.column-main {
width: 61.8%; /* The golden ratio is pretty awesome. */
}

.column-secondary {
width: 38.2%;
}

There's a corollary to this idea, which is that if you set up your container structure well, you won't have to do much horizontal sizing on the contents. You basically let the block-level elements fill the width of their container, as they like to do, and you're all set.

Vertical measurements

Vertical space is more about the structure of the content (i.e. how close elements in the document flow are to one another), and I think these measurements work fine with both fixed and relative units (px or em).

However, using relative units here helps give you a vertical rhythm, which can be very pleasing. It also allows you to make changes to your content (read: font-size) and keep your vertical spacing proportional.

p, ul, ol, dl {
margin: 0 1em; /* gives you proportional spacing above and below,
no matter the font size */
}

Typographic measurements

Font measurements fall into their own category, maybe because font-size acts as the base for all other measurements in em. I've seen advocates for different strategies, but from what I've seen any measurement will work fine, as long as you know what you're doing.

px

Setting font-size in px is extremely reliable and easy to calculate. In the post-IE6 age, it also scales nicely, so there's really no reason not to use px if that's what you prefer.

The only problem I see in using px is that it doesn't take advantage of the CSS cascade. In other words, once I've specified sizes in px, I have to go back and change each one of them individually if I want to make any large-scale changes.

em

Despite any drawbacks, I think em can be a really good way to specify font-size. What I like is that it lets me quickly see the relationship between my font sizes. A lot of times I don't care what the exact size of the font is because the most important thing for me is the relationship of that size to all of the other sizes on the page.

The important thing about using em is to set the sizes as close to the end tag as possible. That means I avoid setting font units on containers:

aside { font-size: 0.8em; } /* This can mess me up */
...
aside p { font-size: 0.8em; } /* Way too small! */

And mostly set sizes on headings and text items:

h1 { font-size: 2.5em; }
h2 { font-size: 2.1em; }
h3 { font-size: 1.7em; }
...

Anyway, I like that I can see clearly and easily the relationship between the sizes there.

rem

Sizing things based on the browser's base font size seems like the web-standards thing to do, because then you allow for browsers whose optimal base font size might not be 16px. In practice, though, it kind of works the other way. From what I've seen, browsers use 16px as the base font size because that's what everyone expects, and set the actual size of that CSS measurement to look decent in the browser.

The biggest drawback here I see is browser support. If you code for browsers that don't support rem, you'll be adding your rules twice:

p {
font-size: 16px;
font-size: 1rem; /* I kind of hate repeating myself here,
but a good CSS preprocessor might ease that pain. */
}

Font Spacing

Other font measurements are a lot easier to figure out once you've got your font-size since most other font measurements fall into the category of either vertical or horizontal measure. For example:

h1 {
font-size: 2.5em; /* Change this, and everything below stays proportional.
(Use whatever measurement unit you prefer.) */
margin-top: 0.618em;
margin-bottom: 0.3em;
line-height: 1.2; /* The only unit-less measure in CSS */
}

Media queries

In most cases, there is little difference between the way browsers handle em and px in media queries. This holds true even when a user uses text zoom to resize the page.

HOWEVER, if someone has changed the default text size in their browser settings, things behave very differently. See my answer to a related question and my codepen demo for a longer explanation.

In short, while px works well for media queries in most cases, it's definitely safer to go with em.

Other cases

There are certainly cases where the above general comments don't apply. For example, you may find that ems come in handy any time you want things proportional to the font size, like the following:

h1.title {
font-size: 2em;
width: 20em; /* Resizing the font also resizes its container properly. */
background-color: #d00d1e;
}

@media (min-width: 400px) {
h1 {
font-size: 2.5em; /* Woot! Didn't have to touch the width! */
}
}

Or maybe you want to constrain line lengths for readability:

p {
max-width: 42em;
}

Also, as mentioned in other comments, px still works well for borders and things like that. It can also be good for padding, especially when you pair it with box-sizing:

.example {
width: 80%;
box-sizing: border-box; /* Padding is NOT added to total width. Huzzah! */
padding: 10px;
}

Should I use px or rem value units in my CSS?

TL;DR: use px.

The Facts

  • First, it's extremely important to know that per spec, the CSS px unit does not equal one physical display pixel. This has always been true – even in the 1996 CSS 1 spec.

    CSS defines the reference pixel, which measures the size of a pixel on a 96 dpi display. On a display that has a dpi substantially different than 96dpi (like Retina displays), the user agent rescales the px unit so that its size matches that of a reference pixel. In other words, this rescaling is exactly why 1 CSS pixel equals 2 physical Retina display pixels.

    That said, up until 2010 (and the mobile zoom situation notwithstanding), the px almost always did equal one physical pixel, because all widely available displays were around 96dpi.

  • Sizes specified in ems are relative to the parent element. This leads to the em's "compounding problem" where nested elements get progressively larger or smaller. For example:

      body { font-size:20px; } 
    div { font-size:0.5em; }

    Gives us:

      <body> - 20px
    <div> - 10px
    <div> - 5px
    <div> - 2.5px
    <div> - 1.25px
  • The CSS3 rem, which is always relative only to the root html element, is now supported on 99.67% of all browsers in use.

The Opinion

I think everyone agrees that it's good to design your pages to be accommodating to everyone, and to make consideration for the visually impaired. One such consideration (but not the only one!) is allowing users to make the text of your site bigger, so that it's easier to read.

In the beginning, the only way to provide users a way to scale text size was by using relative size units (such as ems). This is because the browser's font size menu simply changed the root font size. Thus, if you specified font sizes in px, they wouldn't scale when changing the browser's font size option.

Modern browsers (and even the not-so-modern IE7) all changed the default scaling method to simply zooming in on everything, including images and box sizes. Essentially, they make the reference pixel larger or smaller.

Yes, someone could still change their browser default stylesheet to tweak the default font size (the equivalent of the old-style font size option), but that's a very esoteric way of going about it and I'd wager nobody1 does it. (In Chrome, it's buried under the advanced settings, Web content, Font Sizes. In IE9, it's even more hidden. You have to press Alt, and go to View, Text Size.) It's much easier to just select the Zoom option in the browser's main menu (or use Ctrl++/-/mouse wheel).

1 - within statistical error, naturally

If we assume most users scale pages using the zoom option, I find relative units mostly irrelevant. It's much easier to develop your page when everything is specified in the same unit (images are all dealt with in pixels), and you don't have to worry about compounding. ("I was told there would be no math" – there's dealing with having to calculate what 1.5em actually works out to.)

One other potential problem of using only relative units for font sizes is that user-resized fonts may break assumptions your layout makes. For example, this might lead to text getting clipped or running too long. If you use absolute units, you don't have to worry about unexpected font sizes from breaking your layout.

So my answer is use pixel units. I use px for everything. Of course, your situation may vary, and if you must support IE6 (may the gods of the RFCs have mercy on you), you'll have to use ems anyway.

Which unit I should use in CSS when designing a web page

Different units depending on context. If there was one that was best for every situation, then there wouldn't be so many units.

As rules of thumb go:

If you are working on screen media:

  • Use % for font sizes
  • Use px for images
  • Use px, %, or em for box sizes
  • Use ratios for line height

If you are working in print media:

  • It might be wise to avoid px (this is not a hard rule by any means) and everything else is fair game. It really depends how much control you want.

CSS font size: relative vs. absolute values. Which to use?

Which to use?

Both. Relative for main body text that users are going to have to read a lot of (so they'll want to be able to read it comfortably); Absolute for text that has to be sized to match other elements on the page that are sized in pixels, such as images.

For relative, ‘%’ and ‘em’ are equally good.

For absolute, always use ‘px’. Never use ‘pt’ for on-screen use, it is only sensible for print stylesheets. It is a pity that ‘pt’ is considered the default unit for font-handling because on the web it is the worst possible choice.

(ETA: Note that since this answer, CSS3 has redefined the ‘physical units’ so that px and pt are always proportional. So this problem no longer matters unless you are concerned about very old browsers.)

Some people don't like the ‘compounding’ effect of relative font sizes. The trick, really, is to use as few font-size changes as you can, to avoid too many nestings. It should be possible to get the relative-to-user's-preferred-size behaviour without the compounding behaviour by using the font-size keywords ‘small’/‘medium’/‘xx-large’/etc., but unfortunately that way you don't get much granularity, and there are still even today differences between how the browsers handle them.

Why em instead of px?

The reason I asked this question was that I forgot how to use em's as it was a while I was hacking happily in CSS. People didn't notice that I kept the question general as I wasn't talking about sizing fonts per se. I was more interested in how to define styles on any given block element on the page.

As Henrik Paul and others pointed out em is proportional to the font-size used in the element. It's a common practice to define sizes on block elements in px, however, sizing up fonts in browsers usually breaks this design. Resizing fonts is commonly done with the shortcut keys Ctrl++ or Ctrl+-. So a good practice is to use em's instead.

Using px to define the width

Here is an illustrating example. Say we have a div-tag that we want to turn into a stylish date box, we may have HTML-code that looks like this:

<div class="date-box">
<p class="month">July</p>
<p class="day">4</p>
</div>

A simple implementation would defining the width of the date-box class in px:

* { margin: 0; padding: 0; }

p.month { font-size: 10pt; }

p.day { font-size: 24pt; font-weight: bold; }

div.date-box {
background-color: #DD2222;
font-family: Arial, sans-serif;
color: white;
width: 50px;
}

The problem

However, if we want to size the text up in our browser the design will break. The text will also bleed outside the box which is almost the same what happens with SO's design as flodin points out. This is because the box will remain the same size in width as it is locked to 50px.

Using em instead

A smarter way is to define the width in ems instead:

div.date-box {
background-color: #DD2222;
font-family: Arial, sans-serif;
color: white;
width: 2.5em;
}

* { margin: 0; padding: 0; font-size: 10pt; }

// Initial width of date-box = 10 pt x 2.5 em = 25 pt
// Will also work if you used px instead of pt

That way you have a fluid design on the date-box, i.e. the box will size up together with the text in proportion to the font-size defined for the date-box. In this example, the font-size is defined in * as 10pt and will size up 2.5 times to that font size. So when you're sizing the fonts in the browser, the box will have 2.5 times the size of that font-size.

Best font size em or px to use for Website and Web apps?

This is an extremely subjective question. In addition, there are more options than just em and px: rem, em, px, vw/vh. Understanding how they all work is the key to picking which one is best for you and you app depending on the situation. Most of the time I use rem/em for responsive reasons, but there are times with vw/vh or px are a better option for me. It totally depends on what you're trying to accomplish.

Font scaling based on size of container

If the container is not the body, CSS Tricks covers all of your options in Fitting Text to a Container.

If the container is the body, what you are looking for is Viewport-percentage lengths:

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly. However, when the value of overflow on the root element is auto, any scroll bars are assumed not to exist.

The values are:

  • vw (% of the viewport width)
  • vh (% of the viewport height)
  • vi (1% of the viewport size in the direction of the root element's inline axis)
  • vb (1% of the viewport size in the direction of the root element's block axis)
  • vmin (the smaller of vw or vh)
  • vmax (the larger or vw or vh)

1 v* is equal to 1% of the initial containing block.

Using it looks like this:

p {
font-size: 4vw;
}

As you can see, when the viewport width increases, so do the font-size, without needing to use media queries.

These values are a sizing unit, just like px or em, so they can be used to size other elements as well, such as width, margin, or padding.

Browser support is pretty good, but you'll likely need a fallback, such as:

p {
font-size: 16px;
font-size: 4vw;
}

Check out the support statistics: http://caniuse.com/#feat=viewport-units.

Also, check out CSS-Tricks for a broader look: Viewport Sized Typography

Here's a nice article about setting minimum/maximum sizes and exercising a bit more control over the sizes: Precise control over responsive typography

And here's an article about setting your size using calc() so that the text fills the viewport: http://codepen.io/CrocoDillon/pen/fBJxu

Also, please view this article, which uses a technique dubbed 'molten leading' to adjust the line-height as well. Molten Leading in CSS



Related Topics



Leave a reply



Submit