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: flex
to 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
-
row
row-reverse
column
column-reverse
-
- the diagram above defines the direction of main axis for all different
flex-direction
properties - 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-content
andalign-items
-
justify-content
handles the main axis -
align-items
handles the main axis
-
- to center child element we add
justify-content: center
andalign-items: center
to 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: flex
to parent div - Add
justify-content: center
to center the main axis - Add
align-items: center
to center the cross axis ## Keep Coding π¨βπ»
Top comments (0)