CSS – Easiest way to center Div horizontally

  • by
horizontal_center_div_html

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>
horizontal_center_div_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.


  1. Base64Encode.io - Realtime Encode your string to Base64 format.
  2. Base64Decode.io - Realtime Decode Base64 data to plain text.
  3. Md5Hash.io - Realtime Encoding in Md5Hash.