To Center A Div
To Center A Div
want to center it (horizontally, vertically, or both). Below are the common ways to center a div in
different contexts:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
.container {
display: flex;
justify-content: center;
height: 100vh;
background-color: lightblue;
.box {
width: 200px;
height: 100px;
background-color: coral;
</style>
</head>
<body>
<div class="container">
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: lightgreen;
.box {
width: 200px;
height: 100px;
background-color: coral;
</style>
</head>
<body>
<div class="container">
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
.box {
margin: 0 auto;
width: 200px;
height: 100px;
background-color: coral;
</style>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container {
display: grid;
place-items: center;
height: 100vh;
background-color: lightpink;
}
.box {
width: 200px;
height: 100px;
background-color: coral;
}
</style>
</head>
<body>
<div class="container">
<div class="box">Centered Div</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
.box {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 100px;
background-color: coral;
body {
height: 100vh;
margin: 0;
background-color: lightyellow;
</style>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
</body>
</html>