liveBook · Manning

Em

As explained in Tiny CSS Projects

The CSS em unit expresses a length relative to the font size of the relevant element or inherited context.

An em is a CSS length that scales with font size. For `font-size`, it uses the parent’s font size: if a parent is `12px`, `font-size: .5em` makes its child’s text `6px`. A rem (“root em”) instead uses the root element’s font size. With a `16px` root size, `4rem` is `64px`. section 4.1.1

Em is useful beyond text. A radio button or check box with `width: 1.75em` and `height: 1.75em` can grow when its font size grows. That matters when the native control changes color through `accent-color` but does not grow with larger text. Replacing its visual styling with `appearance: none` makes room for a custom, text-scaled control while keeping the input in the HTML. section 10.3.3

Listing 10.9 Styled radio and checkbox inputs
input[type="radio"],
input[type="checkbox"] {
  appearance: none;
  background-color: var(--background);
  margin: 0;
  width: 1.75em;
  height: 1.75em;
  border: 1px solid currentcolor;      #1
  display: inline-grid;                #2
  place-content: center;               #2
}
 
input[type="radio"] { border-radius: 50% }
 
input[type="checkbox"] { border-radius: 4px }

The custom radio and check box use `1.75em` for both outer dimensions; their border takes its color from `currentcolor`. section 10.3.3

Size the mark inside a control

Give the control an inner `::before` box with `width: 1em` and `height: 1em`. At an input font size of `16px`, that box is `16px` square. It is smaller than the `1.75em` outer control, and `place-content: center` centers it. At this stage the box is invisible until it receives a visible style, such as a background. section 10.3.5

Em also suits a decorative first letter: `font-size: 6em` enlarges a drop cap relative to its surrounding text. Pairing that size with a short line height and `float: left` lets the paragraph wrap around the letter. section 7.1.3

How Tiny CSS Projects covers it

How deep it goes
Explains em through pixel calculations and worked CSS dimensions, without pursuing CSS sizing rules beyond these examples.
Examples
Shows a `12px` parent producing `6px` text, em-sized radio and check boxes, and a `6em` drop cap.
What it assumes
Introduces em with a parent-and-child font-size calculation, then uses CSS selectors and properties in practical examples.
What you can do after
Build it from scratch: size custom radio and check box visuals so they scale with their text.
How it connects
Connects em to rem, font-size, appearance, pseudo-elements, grid layout, and floats.

Also explained in

Compare how 4 books explain em →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny CSS Projects. The section links point to the parts of the book it draws on.