5 Ways To Center a DIV Using CSS


Here are five different ways to center a DIV using CSS.

First of all, let's create a div in the document.

<body>
   <div></div>
</body>


Then, lets make this div visible by adding width: 200px; height: 100px; and background-color: black;.
div{
width: 200px;
height: 100px;
background-color: black;
}


Now its time to center this div using these five ways:
  1. GRID
  2. FLEXBOX
  3. POSITION
  4. FLEX and MARGIN
  5. GRID and MARGIN

Use GRID To Center a DIV

In the parent element add display: flex; place-content: center; and height: 100vh; properties. Now your div is perfectly in the center using GRID property.
//parent element
body{
display: flex;
place-content: center;
height: 100vh;
}


Use FLEXBOX To Center a DIV

In the parent element, add display: flex; justify-content: center; and
 align-items: center;  and height: 100vh; properties. Now the DIV is again in the center.
//parent element
body{
display: flex;
 justify-content: center;
align-items: center;
height: 100vh;
}


Use POSITION To Center a DIV

In the child element, add position: absolute; top: 50%; left: 50% and transform: translate(-50%,-50%);. The DIV is in the center using the POSITION property.
//child element
div{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);

width: 200px;
height: 100px;
background-color: black;
}


Use FLEX and MARGIN To Center a DIV

In the parent element, add display: flex; and height: 100vh;. And then in the child element, add margin: auto;. The DIV is in the center using only FLEX and MARGIN.
//parent element
body{
display: flex;
height: 100vh;
}

//child element
div{
margin: auto;
width: 200px;
height: 100px;
background-color: black;
}


Use GRID and MARGIN To Center a DIV

In the parent element, add display: grid; and height: 100vh;. Then in the child element, add margin: auto;. The DIV is in the center.
//parent element
body{
display: grid;
height: 100vh;
}

//child element
div{
margin: auto;
}


Trending Posts

5 Awesome Computer Shortcut Key Tricks You Must Try

What Are The Use of Function Keys F1 to F12 on The Keyboard?

Is Web Development Dying In 2022?

Why iPhones Don't Have Memory Card Slots?

Why Do All Celebrities Use iPhones?

12MP vs 48MP vs 64MP vs 108MP | Does More Megapixel Equal Better Image Quality?

5 Tips To Become A Computer Genius | How To Become A Computer Genius?

Can I Start Coding At The Age of 30, 40 or 50?

How To Make Your Computer Fast?

How To Take Screenshot On HP, Dell, Asus Laptop And PC?