DEV Community

Cover image for Dark Art of centering elements in CSS
Mandeep Singh Panwar
Mandeep Singh Panwar

Posted on

Dark Art of centering elements in CSS

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 -Alt Text
  • 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
  • Alt Text
  • 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 and align-items
    • justify-content handles the main axis
    • align-items handles the main axis
  • to center child element we add justify-content: center and align-items: center to the parent css
  • and voila!! child div is centered
  • Alt Text

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)