I prefer using flexbox for positioning items and it’s so easy to layout items even if you are starting with CSS. Flexbox always layout child items in one direction i.e you can either layout items horizontally or vertically.
To align-items, first, we need to set the display
property of container and set its value to flex
div { display: flex; }
Now, we have told the browser to treat the container element as flexbox
, let’s see the options to specify the direction of child elements
To layout child items of flex container in either direction, you first need to specify flex-direction
property.
If you omit the flex-direction
property, it defaults to row
which means the child items are going to be laid in the same row, horizontally.
<div style={{ display: 'flex' }}> <div style={{ background: 'grey', padding: '10px' }}>First</div> <div style={{ background: 'orange', padding: '10px' }}>Second</div> </div>
As you can see in the above example the second item is placed next to the first one, horizontally.
If we set the flex-direction
property to column
the second item is going to be placed below the first item as follows
<div style={{ display: 'flex', 'flex-direction': 'column' }}> <div style={{ background: 'grey', padding: '10px' }}>First</div> <div style={{ background: 'orange', padding: '10px' }}>Second</div> </div>
Apart, from row
and column
values flex-direction
also accepts row-reverse
and column-reverse
values. Yes, you are thinking correctly, these values will reverse the default direction of flex items. Lets clear any doubts with below examples
To layout items in reverse order on a row, we need to set flex-direction
to row-reverse
<div style={{ display: 'flex', 'flex-direction': 'row-reverse' }}> <div style={{ background: 'grey', padding: '10px' }}>First</div> <div style={{ background: 'orange', padding: '10px' }}>Second</div> </div>
How, cool is that? Just by changing the value from row
to row-reverse
the items got automatically positioned to right. Not only that the order of elements is also reversed i.e. Second div
is positioned before the First one.
column-reverse
also function similar to row-reverse
. To visualize the things I set the height of parent div
to 100%
<div style={{ display: 'flex', 'flex-direction': 'column-reverse', height: '100%' }} > <div style={{ background: 'grey', padding: '10px' }}>First</div> <div style={{ background: 'orange', padding: '10px' }}>Second</div> </div>
Flexbox is like a blessing for the frontend developers who are not having experience or interest in UI design. As we can see the items can be positioned easily on UI - gone are the days when UI didn’t work as expected.
I hope you enjoyed the article!! 😃