CSS – Horizontally Center a Div

To horizontally center an inner div in an outer div using CSS, follow these instructions.

  • Set a specific width for the inner div
  • Set left and right margins as auto for the inner div.

Example

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        #outer {
            background: #e0ccff;
            padding: 20px;
        }
        #inner {
            height:150px;
            width: 50%;
            margin-left: auto;
            margin-right: auto;
            background: #a065ff;
        }
    </style>
</head>
<body>
    <div id="outer">
        <div id="inner">
        </div>
    </div>
</body>
</html>

background colors, height and padding are for demonstration purpose only. They are not part of the solution. We may modify these, or other properties as per requirement.

Conclusion

In this CSS Tutorial, we learned how to horizontally center an inner div in an outer div using CSS.