/

How to Prevent a Flex Child from Filling the Entire Height

How to Prevent a Flex Child from Filling the Entire Height

In a horizontal list of items, sometimes a line of text can expand to two lines, causing additional space and causing its flex siblings to extend to full height. However, there is a simple solution to this problem.

First, let’s take a look at the code before making any changes:

1
2
3
4
5
6
7
8
9
<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>

To fix the issue, we need to add the self-start class to the code blocks. In Tailwind CSS, this class applies the CSS rule align-self: start;. This will ensure that the flex child does not fill the entire height. The updated code will look like this:

1
2
3
4
5
6
7
8
9
<li class="flex">
<code class="flex-none text-sm whitespace-normal mr-2 mt-0.5 bg-white text-black p-1 self-start">
{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 self-start">
{post.tag}
</code>
<a href={'/' + post.url + '/'}>{post.title}</a>
</li>

By adding the self-start class, the <code> elements will align to the top of the flex container, ensuring that the flex siblings do not extend to full height.

This fix will result in a cleaner and more visually appealing layout, as shown in the image below:

After

Tags: flexbox, CSS, web development