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 Fake Facebook Login Clone Using Only HTML and CSS?

The Importance of Responsive Web Design for Mobile Devices

How To Create A Trapezium Using HTML and CSS?

How To Create A Semi-circle Using Only HTML and CSS?

Building an Enhanced To-Do List App Using HTML, CSS, and JavaScript with Local Storage

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

Web-Based Development Environments: Should You Make the Switch?

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

How To Create A Parallelogram Using HTML and CSS?

Brief History Of Computer