๐ง๐ต๐ฒ ๐ฃ๐ผ๐๐ฒ๐ฟ ๐ข๐ณ ๐๐ฎ๐๐ฒ๐น๐ถ๐ป๐ฒ ๐๐ฟ๐ถ๐ฑ๐ You want your website to look balanced and intentional. A baseline grid helps you achieve this. It's an invisible lattice that keeps all whitespace in sync.
When you add images, things get tricky. Images have their own height based on their aspect ratio. This can push everything after them out of rhythm. Until recently, the only fix was using JavaScript. But now, you can use modern CSS to snap images to the grid.
To start, you need a global line-height on the html element. This makes every line of copy one line box tall. You can use the root line height (rlh) as a unit. It's a variable that controls every vertical measure on the page.
You can also derive a finer grid from the line height. This is useful for spacing and aligning elements. For example, you can use a third of the line height as a baseline unit.
To align images, you need to know their width and aspect ratio. You can use advanced attr() and container queries to get this information. Then, you can round the image height up to the next line using the round() function.
Here's an example:
is not allowed, using plain text instead
You can use the following code to align images:
.baseline-media img {
--w: attr(width px, 400px);
--ar: attr(width type(<number>), 4) / attr(height type(<number>), 3);
--rendered-w: min(100cqw, var(--w));
width: var(--rendered-w);
height: round(up, calc(var(--rendered-w) / (var(--ar))), 1rlh);
object-fit: cover;
}
Note: This technique is Chromium-only for now. In other browsers, images will fall back to their natural size.
Source: https://dev.to/simoncoudeville/aligning-images-to-a-baseline-grid-with-modern-css-5fi4