Site icon ParallelCodes

CSS – Easiest way to center Div horizontally

Let’s see how we can center the div horizontally by simply providing margin to its CSS.  The margin value when set to “0px auto”, the Html element automatically aligns in the center horizontally. This will adjust the left and right margins of the div evenly respective to its parent alignment.

Html code:

<html>
<head>
<title>Center Div</title>

<style>
.container
{
margin: 0px auto;
background-color:#b8bece;
color: #000;
font-family: Arial, Helvetica, sans-serif;
text-align: center;
width: 500px;
height: 500px;
font-weight: bold;
padding: 50px;
}
body
{
background-color:#3146b1 ;
}
</style>
</head>

<body>

<div class="container">
<span>I'm in center horizontally</span>

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

Center Div Horizontally using CSS

This will make our container (div class) to align in center.
This can fail if the parent element has smaller width than the div which we want to center horizontally.

Exit mobile version