Advanced Flex Box trick that perhaps you don’t know

Kyle Le
2 min readOct 17, 2022

--

Everyone loves Flex Box, they are everywhere. Every one loves to write it, read it and use it. There are a lot of tips and tricks about flex box though. Recently on my hobby project, I’ve come across a simple problem that this Flex Box trick helped me a lot

Let’s look at the flex box first :

I have a flex box with 5 items, let’s call the box is a container and every small box inside is an item

Now when you think about justify the items, what is the first thing that comes in mind ? Well justify-content: space-between for the container right ?

Then it will look like this, but what if I want the first box to be on the left and others on the right ? There are many way to do that, but there is one small trick that very easy to use, we use the selector first-child

.container:first-child {
margin-right: auto;
}

We can do it both ways with the last-child

.container:first-child {
margin-left: auto;
}

What if I want the first box to fill the remaining space of the container ? Easy ! We only need flex-grow: 1 and flex-basis: auto

Hope my tricks can make you understand Flex Box more !

Last Words

Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here

--

--

Kyle Le
Kyle Le

Written by Kyle Le

I’m a Software Engineer who loves to write. My content is based on what I've learned and experienced every day

No responses yet