Skip to content

How to center a div

Updated: at 02:20 AM

How to center a div

Today, you’ll learn 3 ways to center a div or any other HTML element.

For this example, we’ll use the same HTML structure 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 method 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 method 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 method 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;
}