Arranging items with CSS flexbox

タイ / Phan Ngoc Thai
Goalist Blog
Published in
3 min readOct 31, 2023
flexbox demo

In this post, we will take a look on some popular properties of flexbox. You can check reference part for more property.
Flexbox allows you to arrange items inside it in several ways. Grid also has similar functions but it is more suitable for making table.
To use flexbox we have to set display property to flex.

display: flex;

Default behavior of flexbox is that it will make your items display inline and control width of your items.

You can use flex-direction property to control flex container’s direction.

flex-direction: row;            /* inline */
flex-direction: column; /* equal rows */

To align your items on vertical axis, you can use align-items property.

align-items: flex-start; /* top */
align-items: center; /* center */
align-items: flex-end; /* bottom */
align-items: stretch; /* make items to have equal height */
align-items: baseline; /* baseline of the cross axis, it relatives to content inside item ex: text */

To align your items on horizontal axis, you can use justify-content property.

justify-content: flex-start;    /* left */
justify-content: center; /* center */
justify-content: flex-end; /* right */
justify-content: space-between; /* space equally between items */

When your items are too long and can not fit in one line, you can use flex-wrap property for line break. Default is no-wrapping.

flex-wrap: wrap;

To add space between your items, you can use gap property.

gap: 10px;

Flexbox also allows you to control your items individually. For aligning an item:

align-self: flex-start; /* top */
align-self: center; /* center */
align-self: flex-end; /* bottom */

To set initial length of item, you can use flex-basis property.

flex-basis: 200px;

Even you use set initial length for your item. It does not mean that your item has fixed length. Flexbox can change item’s size to make sure items fit inside flexbox. You can use flex-shrink property to avoid this behavior, but be careful with responsive of your page. Fixed width is not a good idea.

flex-shrink: 0;

For controlling item length dynamically, you can use flex-grow. It is convenient when you want an item to capture all remaining space of flexbox.

flex-grow: 1;

Well, that were a lot of properties to remember. You may question that why did I only name a few flexbox properties?
The reason is when you make a responsive website, width is more important. I used most of properties above for flex-direction row. When it comes to flex-direction column, I only use gap to set space between rows. There wasn’t use case that I had to hard set the height and use flex-direction column.

References:

--

--