Yes CSS can be tricky sometimes and with the emergence flex-box and grid, it infact has become more trickier writing advanced CSS codes. I want to quickly work you through how the justify-content
and align-items
properties work in flex-box; when to use them and the output you should expect to get from them.
Now lets write a couple of div tags in our html and then use CSS flex-box on them so as to understand how justify-content
and align-items
properties work.
<div classname="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
Now we shall be using the CSS flex-box properties on these divs and also we would be giving them some colours so that they can be visible.
.container{
display: flex;
}
.container > div{
background: red;
width: 30px;
margin-left: .8rem;
}
With these properties, our container div is going to display flex and since the CSS default flex-direction is row, when we add the justify-content property, the justification will happen along the horizontal axis while the align-items will happen along the vertical axis.
Now let's add these two properties and see their effects.
.container{
display: flex;
justify-content: center;
align-items: center;
}
.container > div{
background: red;
width: 30px;
margin-left: .8rem;
}
Since the default CSS flex direction is row, the justify-content: center property moved the container to the center on the horizontal plane while the align-items: center property moved it to the center on the vertical plane.
Ahah! I can hear you ask "how will it look like if I set flex-direction to column?"
Now let's do that but with only the justify-content property and see for yourself what happens
.container{
display: flex;
flex-direction: column;
justify-content: center;
}
.container > div{
background: red;
width: 30px;
margin-left: .8rem;
}
Since column favours the vertical plane, when you set the the flex-direction: column
, the justify-content: center
property centers the container element along the vertical plane (no longer the horizontal plane as it was when the flex-direction was set to row). Then, the align-items: center
property will center the container element on the horizontal plane (as against the vertical plane when it the flex-direction was set to row).
Rule of thumb
the
flex-direction
property will determine what plane thejustify-content
andalign-items
properties will take effect. If set to column then thejustify-content
property will effect on the vertical plane while thealign-items
property will effect on the horizontal plane but if set to row then reverse is the case for thejustify-content
andalign-items
properties.Flexbox should be used on the parent element alone. So also
justify-content
andalign-items
properties.justify-self
andalign-items
properties should be used for the child of the parent element, if need be.
Read more on CSS flexbox
C:\Program Files\Android\Android Studio
Top comments (0)