Hello folks, this is my first blog π
Alright, lets dive into it.
What will you learn π€
How to magically center anything in FLEXBOX
Lets get to it, then
First create a pen at codepen.io
Lets add some code
- Add this to the html sections
-
<div class="box"> <div class="sm-box"></div> </div> - We have created a πββοΈ parent div of class box which has πΆ child div sm-box
- and this to the css
-
.box {height: 200px; width: 200px; border: 1px solid #c51244;} -
.sm-box{ height: 100px; width: 100px; background-color: red; } - It will look like this
-
this css is used for us to see πΆchild div layout in πββοΈparent div
We are ready now
Flexbox basics π
- In order to use flex box u must add
display: flexto the parent div i.e.box - Flex box uses two axis to layout out elements
- main axis
- cross axis
- flexbox uses flex direction property to define the main axis, it takes any of these value
-
rowrow-reversecolumncolumn-reverse
-

- the diagram above defines the direction of main axis for all different
flex-directionproperties - by default (when not defined) flex-direction is
row
Alright we are done with theory lets center our πΆ child div now
- Since now u know about axis and flex-direction, we can move on to the main properties
justify-contentandalign-items-
justify-contenthandles the main axis -
align-itemshandles the main axis
-
- to center child element we add
justify-content: centerandalign-items: centerto the parent css - and voila!! child div is centered
Overview
- In order to center all elements inside a parent element u can use flexbox
- Add
display: flexto parent div - Add
justify-content: centerto center the main axis - Add
align-items: centerto center the cross axis ## Keep Coding π¨βπ»
Top comments (0)