Skip to content

How to center a div

Published: at 10:43 PM

How to center a div

Today you will learn 3 ways to center a div or any other HTML object.

For this example, we’ll use the same HTML base for all 3 CSS methods of centering the div.

Table of contents

Open Table of contents

Base HTML

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Center a div</title>
</head>
<body>
    <div></div> <!-- center a div -->
</body>
</html>

First way using the “display: grid”

/* style.css */
* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

body {
	background-color: #020202;
	width: 100vw;
	height: 100vh;
	display: grid;
	place-items: center;
}

div {
	background-color: deeppink;
	width: 200px;
	height: 200px;
}

Second way using the “display: flex”

/* style.css */
* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

body {
	background-color: #020202;
	width: 100vw;
	height: 100vh;
  	display: flex;
  	align-items: center;
  	justify-content: center;
}

div {
	background-color: deeppink;
	width: 200px;
	height: 200px;
}

Third way using the “transform: translate”

/* style.css */
* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

body {
	background-color: #020202;
  	position: absolute;
  	top: 50%;
  	left: 50%;
  	transform: translate(-50%, -50%);
}

div {
	background-color: deeppink;
	width: 200px;
	height: 200px;
}