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

Is Web Development a Good Career?

How Long Does It Take to Learn Programming?

Easy Light Bulb Project: HTML, CSS, and JavaScript

How to Become a Web Designer: A Complete Guide

60hz vs 90hz vs 120hz | Which One is Best? | What is Refresh Rate?

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

Brief History Of Computer

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

Is HTML a Programming Language?

Shield Your Small Business: Must-Have Cybersecurity Strategies