The Simplest Possible Way to Create a CSS Baseline Grid Without Going Crazy
Posted by Dustin Boston on in CSS.
- There is a calculation you can do to get a pretty good CSS baseline grid.
- But it’s not perfect. For that you need to find the baseline ratio.
- Then multiply the font size by the baseline ratio.
- This gives you the baseline offset.
- But that’s super complicated and I forget how to do it every time.
- The simplest way to get a solid baseline grid is to eyeball it.
- Start by slapping this background image on the body:
body.grid {
background-image: repeating-linear-gradient(
0deg,
magenta,
magenta 1px,
transparent 1px,
transparent
);
background-size: 24px 24px;
}
- That gives you a grid with a line-height of 24px. You can change it.
- Then add margin to the top of each block element until the bottom of the text sits on a grid line.
- Finally add padding (to prevent margin collapsing) to the bottom of the block element until its box touches the next grid line.
- Trust me, the math doesn’t matter. What matters is what you see.
- Images are more challenging. But modern CSS helps out.
- I’ve used something like this bit of code to constrain images to the baseline:
figure {
width: 250px;
height: calc(var(--baseline) * 8);
img {
width: 100%;
object-fit: cover;
}
}
- But the easiest way is to just crop the image to the correct dimensions.