How to horizontally center a div using CSS?

In web development, aligning element property is crucial to create visually appealing and user-friendly designs. There are multiple way to achieve this. we used most popular methods "margin: auto"

HTML

Code :
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Horizontally center a div</title>
  </head>

  <style>
    .outer {
      height: 400px;
      background-color: green;
    }

    .inner {
      height: 200px;
      background-color: red;
      width: 50%;
      margin: 0 auto;
    }
  </style>

  <body>
    <div class="outer">
      <div class="inner"></div>
    </div>

  </body>
</html>


Define a div with class outer and inside outer div define another div class inner div. Apply basic CSS such as background-color and height to differentiate both div.

now margin: 0 auto; margin  auto distribute the remaining space evenly.


Second Method


CSS:
.outer{
    height: 400px;
    background-color: green;
    display: flex;
    justify-content: center;
}

.inner{
    height: 200px;
    background-color: red;
    width: 50%;
}

use this CSS in <style></style> tag where display: flex; justify-content: center; in outer class.

Remember one thing "display" have some own property which can affect your div if you have more than one div.



Some other method are also used

other method also used to centralize element such as Position method. Where we adjust div by Top, Bottom, Right, Left.

CSS:
.outer{
    width: 800px;
    height: 400px;
    background-color: green;
    position: relative;
}

.inner{
    height: 400px;
    background-color: red;
    width: 400px;
    position: absolute;
    left: 200px;
}


.outer div have position: relative; and .inner div position: absolute; and left: 200p; to center the div.


Transform Method

In In this Method we use transform property of CSS. which make div center or middle of another div.

Center

Make second div center of first div.
CSS:
.outer{
    width: 800px;
    height: 400px;
    background-color: green;
}

.inner{
    height: 200px;
    background-color: red;
    width: 400px;
    transform: translate(200px, 0);
}


Middle 

Make second div middle of first div
Code :

.outer{
    width: 800px;
    height: 400px;
    background-color: green;
}

.inner{
    height: 200px;
    background-color: red;
    width: 400px;
    transform: translate(200px, 100px);
}


transform: translate(200px, 100px); translate have two property just like x, y and it adjust by that co-ordinate.

Comments