How to have a flex child not fill entire height

By

Learn how to stop a flex child from stretching to fill the full height of its row by applying align-self start, or the self-start class in Tailwind CSS.

~~~

To stop a flex child from stretching to the full height of its row, set align-self: flex-start on that child. In Tailwind CSS, that’s the self-start class.

Here’s the problem I ran into. I had a horizontal list of items, and if a line of text got to 2 lines, I had some additional space and its flex siblings were extending to full height:

Before

This was the code:

<li class="flex">
  <code class="flex-none text-sm whitespace-normal mr-2 mt-0.5 bg-white text-black p-1 ">
    {new Date(post.date).toString().slice(4, 11)}
  </code>{' '}
  <code class="flex-none text-sm whitespace-normal mr-2 bg-black text-white border p-1 ">
    {post.tag}
  </code>
  <a href={'/' + post.url + '/'}>{post.title}</a>
</li>

Why does this happen?

A flex container aligns its children along the cross axis using the align-items property. Its default value is stretch.

With the default flex-direction: row, the cross axis is vertical. So every child stretches to match the height of the tallest sibling in the row. That’s why the two code labels grew when the title wrapped to a second line.

This default is often what you want. It’s what makes equal-height columns so easy with flexbox. Here it worked against me.

The fix

The align-self property overrides the container’s align-items value for a single child. Set it to flex-start and the element keeps its natural height, aligned to the top of the row.

To fix this, I added the self-start class to the code blocks, which in Tailwind CSS applies align-self: flex-start:

After

In plain CSS, without Tailwind, the same fix looks like this:

.date-label {
  align-self: flex-start;
}

If you want every child to behave this way, skip align-self and set align-items: flex-start on the container instead. In Tailwind that’s items-start on the flex parent.

One thing to watch: flex-start pins the child to the top of the row. If you’d rather have it vertically centered, use align-self: center, which is self-center in Tailwind. I picked flex-start here because the labels needed to line up with the first line of the title.

Tagged: CSS · All topics
~~~

Related posts about css: