How to center div in HTML page using CSS

  • by
center div in html css

Hi friends, in this post we will see one of the most easiest way to center HTML div both horizontally and vertically. We often face this issue while designing. In this post, I will share a simple CSS design to center our HTML div.

DOWNLOAD DESIGN

center div in html css

center div in html css

Create a simple HTML page with below code:

index.html:

<html>
<head>
<title>User Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />

</head>
<body>
<div class="wrapper1">

<div class="logincontainer">
<h3>USER LOGIN</h3>
<hr />
<input type="text" class="form-control" placeholder="Enter your UserId" />
<br />
<input type="text" class="form-control" placeholder="Enter your Password" />
<br />
<input type="button" class="btn btn-info form-control" value="Login"/>
</div>

</div>
</body>
</html>

We will set the wrapper1 div to occupy the full width and height of the client and make our logincontainer in center.

Add the following css in the head section of your html:

<style>
body {
background-color: #f5f5f5 !important;
height: 100vh !important;
}

.wrapper1 {
height: 100vh !important;
display: flex;
align-items: center;
flex-direction: column;
justify-content: center;
width: 100%;
padding: 20px;
}

.logincontainer {
border-radius: 0px !important;
background: #fff;
width: 90%;
max-width: 450px;
position: relative;
padding: 20px;
border: 1px white solid;
box-shadow: 0 15px 10px -10px rgba(31, 31, 31, 0.5);
text-align: center;
}

</style>

The final result will be like below:

center div in html css

center div in html css

The full page will look like below:

index.html:

<html>
<head>
<title>User Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />

<style>
body {
background-color: #f5f5f5 !important;
height: 100vh !important;
}

.wrapper1 {
height: 100vh !important;
display: flex;
align-items: center;
flex-direction: column;
justify-content: center;
width: 100%;
padding: 20px;
}

.logincontainer {
border-radius: 0px !important;
background: #fff;
width: 90%;
max-width: 450px;
position: relative;
padding: 20px;
border: 1px white solid;
box-shadow: 0 15px 10px -10px rgba(31, 31, 31, 0.5);
text-align: center;
}

</style>
</head>
<body>
<div class="wrapper1">

<div class="logincontainer">
<h3>USER LOGIN</h3>
<hr />
<input type="text" class="form-control" placeholder="Enter your UserId" />
<br />
<input type="text" class="form-control" placeholder="Enter your Password" />
<br />
<input type="button" class="btn btn-info form-control" value="Login"/>
</div>

</div>
</body>
</html>

DOWNLOAD DESIGN