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

How To Create A Magic 8 Ball Using HTML, CSS, and JavaScript?

Sunrise And Sunset Animation Using HTML & CSS?

8 Characteristics Of Modern Computer

Building A Simple Analog Clock Using HTML, CSS, and JavaScript

Types of Computer

Brief History Of Computer

Supercharge Your Business: Digital Innovation Tactics

Is Learning To Code Boring?

How To Create a Fake Facebook Login Clone Using Only HTML and CSS?

Creating a Netflix-inspired Animation using HTML and CSS