In CSS, line-height
is probably one of the most misunderstood, yet commonly-used attributes. As designers and developers, when we think about line-height
, we might think about the concept of leading from print design — a term, interestingly enough, that comes from literally putting pieces of lead between lines of type.
Leading and line-height
, however similar, have some important differences. To understand those differences, we first have to understand a bit more about typography.
An overview of typography terms
In traditional Western type design, a line of text is comprised of several parts:
- Baseline: This is the imaginary line on which the type sits. When you write in a ruled notebook, the baseline is the line on which you write.
- Descender: This line sits just below the baseline. It is the line that some characters — like lowercase
g
,j
,q
,y
andp
— touch below the baseline. - X-height: This is (unsurprisingly) the height of a normal, lowercase
x
in a line of text. Generally, this is the height of other lowercase letters, although some may have parts of their characters that will exceed the x-height. For all intents and purposes, it serves as the perceived height of lowercase letters. - Cap-height: This is the height of most capital letters on a given line of text.
- Ascender: A line that oftentimes appears just above the cap height where some characters like a lowercase
h
orb
might exceed the normal cap height.
Each of the parts of text described above are intrinsic to the font itself. A font is designed with each of these parts in mind; however, there are some parts of typography that are left up to the type setter (like you and me!) rather than the designer. One of these is leading.
Leading is defined as the distance between two baselines in a set of type.
A CSS developer might think, “OK, leading is the line-height
, let’s move on.” While the two are related, they are also different in some very important ways.
Let’s take a blank document and add a classic “CSS reset” to it:
* {
margin: 0;
padding: 0;
}
This removes the margin and padding from every single element.
We’ll also use Lato from Google Fonts as our font-family
.
We will need some content, so let’s an create an <h1>
tag with some text and set the line-height
to something obnoxiously huge, like 300px. The result is a single line of text with a surprising amount of space both above and below the single line of text.
When a browser encounters the line-height
property, what it actually does is take the line of text and place it in the middle of a “line box” which has a height matching the element’s line-height. Instead of setting the leading on a font, we get something akin to padding one either side of the line box.
As illustrated above, the line box wraps around a line of text where leading is created by using space below one line of text and above the next. This means that for every text element on a page there will be half of the leading above the first line of text and after the last line of text in a particular text block.
What might be more surprising is that explicitly setting the line-height
and font-size
on an element with the same value will leave extra room above and below the text. We can see this by adding a background color to our elements.
This is because even though the font-size
is set to 32px, the actual text size is something less than that value because of the generated spacing.
Getting CSS to treat line-height like leading
If we want CSS to use a more traditional type setting style instead of the line box, we’ll want a single line of text to have no space either above or below it — but allow for multi-line elements to maintain their entire line-height
value.
It is possible to teach CSS about leading with a little bit of effort. Michael Taranto released a tool called Basekick that solves this very issue. It does so by applying a negative top margin to the ::before
pseudo-elementand a translateY
to the element itself. The end result is a line of text without any extra space around it.
The most up-to-date version of Basekick’s formula can be found in the source code for the Braid Design System from SEEK. In the example below, we are writing a Sass mixin to do the heavy lifting for us, but the same formula can be used with JavaScript, Less, PostCSS mixins, or anything else that provides these kinds of math features.
@function calculateTypeOffset($lh, $fontSize, $descenderHeightScale) {
$lineHeightScale: $lh / $fontSize;
@return ($lineHeightScale - 1) / 2 + $descenderHeightScale;
}
@mixin basekick($typeSizeModifier, $baseFontSize, $descenderHeightScale, $typeRowSpan, $gridRowHeight, $capHeight) {
$fontSize: $typeSizeModifier * $baseFontSize;
$lineHeight: $typeRowSpan * $gridRowHeight;
$typeOffset: calculateTypeOffset($lineHeight, $fontSize, $descenderHeightScale);
$topSpace: $lineHeight - $capHeight * $fontSize;
$heightCorrection: 0;
@if $topSpace > $gridRowHeight {
$heightCorrection: $topSpace - ($topSpace % $gridRowHeight);
}
$preventCollapse: 1;
font-size: #{$fontSize}px;
line-height: #{$lineHeight}px;
transform: translateY(#{$typeOffset}em);
padding-top: $preventCollapse;
&::before {
content: "";
margin-top: #{-($heightCorrection + $preventCollapse)}px;
display: block;
height: 0;
}
}
At first glance, this code definitely looks like a lot of magic numbers cobbled together. But it can be broken down considerably by thinking of it in the context of a particular system. Let’s take a look at what we need to know:
$baseFontSize
:This is the normalfont-size
for our system around which everything else will be managed. We’ll use 16px as the default value.$typeSizeModifier
: This is a multiplier that is used in conjunction with the base font size to determine thefont-size
rule. For example, a value of 2 coupled with our base font size of 16px will give usfont-size: 32px
.$descenderHeightScale
: This is the height of the font’s descender expressed as a ratio. For Lato, this seems to be around 0.11.$capHeight
: This is the font’s specific cap height expressed as a ratio. For Lato, this is around 0.75.$gridRowHeight
: Layouts generally rely on default a vertical rhythm to make a nice and consistently spaced reading experience. For example, all elements on a page might be spaced apart in multiples of four or five pixels. We’ll be using 4 as the value because it divides easily into our $baseFontSize of 16px.$typeRowSpan
: Like$typeSizeModifier
, this variable serves as a multiplier to be used with the grid row height to determine the rule’sline-height
value. If our default grid row height is 4 and our type row span is 8, that would leave us with line-height: 32px.
Now we can then plug those numbers into the Basekick formula above (with the help of SCSS functions and mixins) and that will give us the result below.
That’s just what we’re looking for. For any set of text block elements without margins, the two elements should bump against each other. This way, any margins set between the two elements will be pixel perfect because they won’t be fighting with the line box spacing.
Refining our code
Instead of dumping all of our code into a single SCSS mixin, let’s organize it a bit better. If we’re thinking in terms of systems, will notice that there are three types of variables we are working with:
Variable Type | Description | Mixin Variables |
---|---|---|
System Level | These values are properties of the design system we’re working with. | $baseFontSize $gridRowHeight |
Font Level | These values are intrinsic to the font we’re using. There might be some guessing and tweaking involved to get the perfect numbers. | $descenderHeightScale $capHeight |
Rule Level | These values will are specific to the CSS rule we’re creating | $typeSizeMultiplier $typeRowSpan |
Thinking in these terms will help us scale our system much easier. Let’s take each group in turn.
First off, the system level variables can be set globally as those are unlikely to change during the course of our project. That reduces the number of variables in our main mixin to four:
$baseFontSize: 16;
$gridRowHeight: 4;
@mixin basekick($typeSizeModifier, $typeRowSpan, $descenderHeightScale, $capHeight) {
/* Same as above */
}
We also know that the font level variables are specific to their given font family. That means it would be easy enough to create a higher-order mixin that sets those as constants:
@mixin Lato($typeSizeModifier, $typeRowSpan) {
$latoDescenderHeightScale: 0.11;
$latoCapHeight: 0.75;
@include basekick($typeSizeModifier, $typeRowSpan, $latoDescenderHeightScale, $latoCapHeight);
font-family: Lato;
}
Now, on a rule basis, we can call the Lato
mixin with little fuss:
.heading--medium {
@include Lato(2, 10);
}
That output gives us a rule that uses the Lato font with a font-size
of 32px and a line-height
of 40px with all of the relevant translates and margins. This allows us to write simple style rules and utilize the grid consistency that designers are accustomed to when using tools like Sketch and Figma.
As a result, we can easily create pixel-perfect designs with little fuss. See how well the example aligns to our base 4px grid below. (You’ll likely have to zoom in to see the grid.)
Doing this gives us a unique superpower when it comes to creating layouts on our websites: We can, for the first time in history, actually create pixel-perfect pages. Couple this technique with some basic layout components and we can begin creating pages in the same way we would in a design tool.
Moving toward a standard
While teaching CSS to behave more like our design tools does take a little effort, there is potentially good news on the horizon. An addition to the CSS specification has been proposed to toggle this behavior natively. The proposal, as it stands now, would add an additional property to text elements similar to line-height-trim
or leading-trim
.
One of the amazing things about web languages is that we all have an ability to participate. If this seems like a feature you would like to see as part of CSS, you have the ability to drop in and add a comment to that thread to let your voice be heard.
Very interesting technique! Containing elements will require top/bottom padding to ensure the text doesn’t overflow.
Are you aware of any down-sides? i.e. performance hit from the extra styles being applied to a text-heavy page?
Interesting approach, any idea on how much the adjustments affect performance? I feel like it would add additional layout time?
I attempted to take line height in a simpler way, just ensuring vertical rhythm is consistent:
https://medium.com/creative-technology-concepts-code/css-vertical-rhythm-with-typography-units-e2c3482a4ac0
I wasn’t really sure where this article was trying to achieve, was getting pretty bored .
But my interest for typography on the web kept me going…
Oh boy! Thank f!@% I did!
This literally blew my mind! Bravo!
The future is a illustrator(tm) for designing web, with a JavaScript and sass engine!
Holy moly!
This is a really detailed article, and it’s clear you put a ton of work into it.
I would encourage you refactor the mixin to use unitless values for line height and relative units for font size. You can achieve the same pixel-grid lockup via setting a ratio using the same approach with your mixin logic.
The reason for suggesting this is absolute values, especially for line heights, can be problematic for people who zoom or otherwise modify their font size to be able to read it. By maintaining proportions in the output CSS, you’re guaranteeing a wider range of support for browsing mode and context.
If anyone is interested, here is vanilla CSS approach for aligning type on baseline grid:
In mixin:
padding-top: $preventCollapse;
In result:
padding-top: 1;
— invalid property value )Is this rule necessary? When this rule is (and applied), a pixel parasite appears between the headers :(
Great article! Thanks for this, I’ll definitely use it in current and future projects. It’s very similar to Codyhouse’s line-height crop (https://codyhouse.co/ds/globals/typography) and Eightshapes text crop tool (http://text-crop.eightshapes.com/?typeface-selection=custom-font&typeface=Lato&custom-typeface-name=IBM%20Plex%20Serif&custom-typeface-url=http%3A%2F%2Fwww.paulrand.design%2Fhome%2Fdlewand691%2Fwww.paulrand.design%2Fnode_modules%2F%40ibm%2Fplex%2FIBM-Plex-Serif%2Ffonts%2Fsplit%2Fwoff2%2FIBMPlexSerif-Regular-Latin1.woff2&custom-typeface-weight=400&custom-typeface-style=normal&weight-and-style=100&size=51&line-height=1.2&top-crop=13&bottom-crop=12).
Thanks Daniel! If you want to read more about my approach check this out: https://medium.com/eightshapes-llc/cropping-away-negative-impacts-of-line-height-84d744e016ce
It doesn’t try to work like a design tool, it simply removes the top and bottom space from a block of text. Slightly different goal than basekick I think.
This is a great approach, and the first I saw of this was on Mark’s twitter account :D
I have a question though: is it possible to replicate this approach in Figma?
As far as I can see, Figma line-heights behave like the web1; so to do this in Figma is kinof like a big hack, which defeats the whole purpose of this.
If anyone is using such a workflow, would like some pointers on how to do the same :)
Hey Palash!
I’ve been going down this rabbit hole as well and also came to the same conclusion.
There is a workaround for this but it’s not perfect. The solution is pretty well documented here: https://uxdesign.cc/the-4px-baseline-grid-89485012dea6 and Figma has a little bit about this here: https://www.figma.com/best-practices/everything-you-need-to-know-about-layout-grids/baseline-grids/
What I’ve begun to realize though is that at the end of the day if you have to add a workaround to CSS and to Figma to get baseline grids to work properly it makes you question if the pursuit of the baseline grid is worth it lol.
What I’ve been doing is just setting up the vertical grid to work with the line boxes in Figma and adjust the spacing of other elements accordingly. Until there is native CSS support for this I don’t Figma changing its line-height property.
While interesting, it’s totally useless. The typesets have a reason for leaving a gap above and below. While it may not have a use in a language with a limited repertoire of characters, there are languages using characters with accents and other appendages, like French: ÊÉÈ or Ç. In my native language we boast glyphs like ĚŠČŘŽÝÁÍÉ… Oh.. It appears some are not even supported by the font. You see the little thing above the S to make a Š? Well that accent should be above the Ě, Č and Ř as well.
That it doesn’t cover the use case of accents in capital letters hardly makes this useless :) It could use a fix, sure. Maybe just increasing $capHeight?
Author of Megatype here. We worked on a similar problem a few years ago: measuring typographic spacing from the baseline to the cap height of the following line. A major difference I noticed is that where you’re specifying a descender size we simply used a y-offset to shift fonts with long descenders on the y axis. I think your approach is more sophisticated.
However — from memory — there was an issue that stopped us dead in our tracks, which was discovering that — more often than you’d expect — there are fonts out there that have poorly set up metrics. What this can mean is that unfortunately they’re likely to render differently on windows compared to mac, as these sometimes look at totally different metrics, and its hard to see how this could be solved with just CSS. For us it was seeing a website render beautifully on mac, but on windows one typeface moved down a few px while to other moved up a few. Damn…
I eventually reached a disappointing conclusion: it can’t be done reliably in CSS. Not without JS, and not without better native CSS typographic properties (check out the ch and ex units — there are also proposals for a native cap height unit I have contributed to). But this was a few years ago and I am by no means an expert. It does begin to get exponentially more complex once font metrics tables need to be part of the solution though.
More on what we were doing here:
https://medium.com/@tbredin/a-jolly-web-typesetting-adventure-42948ab0d1dd
I believe the definition of leading is wrong. It’s the added distance between lines, that is between descender and ascender. In manual typesetting, this was done by adding a strip of lead between each line.
From Wikipedia, “In hand typesetting, leading is the thin strips of lead that were inserted between lines of type in the composing stick to increase the vertical distance between them. The thickness of the strip is called leading and is equal to the difference between the size of the type and the distance from one baseline to the next. For instance, given a type size of 10 points and a distance between baselines of 12 points, the leading would be 2 points.”
Great article, my recommendation would be to include a visual for calculating descender and cap heights.
Revisiting this technique again. How about varied elements like images? How can those be adjusted to always fit the baseline?
A font-family definition normally includes several fonts and a generic font name as a last option, like:
When the used fonts have different metrics this technique values probably fails if the client does not the first from the list.
I think it would be nice to have CSS properties that are based on the intrinsic metrics of fonts, for example to set a height based on the baseline. Or trim empty pixels when using
text-justify:inter-character
.Bless your heart.
A follow-up question to all of this: how does one deal with the horizontal alignment issues one may often face when trying to align 2 lines or more lines of text.
One of your examples above illustrates this perfectly. Screenshot here: https://imgur.com/a/mt5jHEI
How do we ensure that the first character of the first line always aligns with the first character of the second line, regardless of what letter each starts with?
It seems to me the only way to do this is with margin or translate offsets, which need to be determined per-character. In other words, you may offset the first line for the ‘H’ by -3px or whatever, but then it won’t work for a ‘D’ necessarily.
Am I making sense? Someone please help! I’m in typographic hell over here. Thank you!