I’m All About That Base…line

Background

You may have noticed that some of your favorite websites, like Google Now and Pintrest, have started to put small amounts of content into discrete divs. These small units of content are called cards and the card UI pattern is gaining traction because they are scalable and easy to manipulate.

A while back, I implemented this design:

1
2
3
4
5
6
.card {
  display: inline-block;
  background-color: #89b1b5;
  padding: 10px;
  margin: 5px;
}
1
2
3
4
5
6
<div class="card">
  <img src="picture.jpeg" />
</div>
<div class="card">
  <p>Lorem ipsum</p>
</div>

I imagined that this would look okay. Instead, it looked like this:

Q: Why do bad things happen to good HTML elements?

A: Because we live in a cruel world where nothing has meaning.

Wha?

So it turns out that images have a veritical-align property that defaults to baseline. You might be asking, “WHAT IS A BASELINE?!?”

First off, calm down. We’re going to get through this together.

Okay, do you remember writing on college-ruled paper in school or are you reading this in the future where everyone comminucates via brain chips and Kanye West is worshipped as a god? Well, if you remember ruled paper, those blue lines are perfect examples of baselines. Letters like p, q, and y have appendages that exend below the baseline but most letters sit on it.

For instance, the teal line in this image is the baseline:

Keep in mind that the vertical-align property does not affect the positioning of the element’s contents. Rather, it affects the element’s alignment on the page. If you want to vertically center its contents, adding vertical-align: middle will have absolutely no effect. Which is inconsistant, really, considering that text-align: center will. The W3C must contain some evil maniac just trying to drive us crazy. WE MUST NOT LET THEM!!!

…anyway, for my simple demo the image’s default alignment of baseline was causing the strange behaviour. The image was trying to line up with the baseline of the text in the div to its right, causing the left-hand div to be higher than the right-hand div.

Solution

A quick way to solve this is to override the image default:

1
2
3
.card img {
  vertical-align: middle;
}

To learn more about the vertical-align property, checkout Impressive Web’s blog or CSS-Trick’s article.

Throwback

All hail the You’ve Got Mail flash intro!