Signup/Sign In
LAST UPDATED: AUGUST 5, 2021

How to align a DIV horizontally center using CSS

Answer: Using CSS margin Property

The HTML div can be aligned to left, right, or center using CSS property. The method to center div varies depending on the condition that either you want to horizontally center it or vertically center it. Here in this tutorial, we will learn about the CSS properties used to horizontally center the div element.

We can use the CSS margin property to align the div horizontally center. Use margin: auto to <div> element to the center is horizontal. The margin: auto value equally adjusts the margin at left and right.

Example: Program to align div horizontally center using the margin property

In this program, we will horizontally center div using margin: auto property.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CSS</title>
</head>
<style>   
  .container {
    width:500px;
	margin: auto;
	border: 3px solid blue;
  }
  h2, p {
     text-align: center;
  }   
</style>
<body>
    <h2> horizontally centered div using CSS </h2>
    <div class="container">
     <p> The div is horizontally centered </p> 
	</div>	
</body>
</html>

Output:

Here is the output of the above program.

Using flexbox

The flexbox can also be used to align the div element horizontally. Use display: flex along with justify-content:center to center align div container. Also, use align-items:center with it.

Example: Horizontally center using flexbox

In this example, we have center-aligned the inner div within the outer div using flexbox property.

Conclusion

In this tutorial, we have learned to center align the div element using CSS. There are various methods to do so. Here we have explained the simplest method to do so. Use margin property or flexbox property to horizontally center div.



About the author: