How to align a DIV vertically and horizontally center?

How to align a DIV vertically and horizontally center

We can achieve this in two ways, one with the flex method and the other with Pure CSS


First, we will see the flex method: Using the flex method all you need to include below three CSS properties

display:flex;
justify-content:center;
align-items:center;

Please refer to the below example

CODE

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.parent{
display:flex;
justify-content:center;
align-items:center;
background-color:#4a483d;
border:1px solid #000;
color:#fff;
height:300px;

}
.child{
border:1px solid #fff;
padding:20px;
}
</style>
</head>
<body>
<div class="parent">
    <div class="child">Your Content Is Here</div>
</div>
</body>
</html>

Page Title
Result
Your Content Is Here

Now, Using Pure CSS all you need to include below properties

position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);

Please refer to the below example

CODE

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.main{
position:relative;
height: 99vh;
background-color:#4a483d;
}
.demo{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
background-color:#fff;
border:2px solid #000;
padding:20px;
}
</style>
</head>
<body>
<div class="main">
  <div class="demo">Your Content Is Here</div>
</div>
</body>
</html>
Page Title
Result
Your Content Is Here

Write a comment