Signup/Sign In

How to center align absolute positioned div using CSS?

The element with the position: absolute CSS property is positioned relative to its nearest ancestor. We can also align the absolute positioned div element within the center by specifying the CSS property left along with the position: absolute property. The CSS left property will work only when we have already specified the position property.

In this tutorial, we will be learning about these properties.

Using CSS left properties

The absolute positioned div can be aligned to the center using CSS left properties. To do so add position: absolute to container class and position:relative to the child element. Now for center alignment add left:50% to the parent class and left:-50% to the child element.

Example: Center align absolute positioned div using left properties

In this program, we have used left properties to center align the absolute positioned div.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
    h2 {
	  text-align: center;
	}
	.container {
	  position: absolute;
      left: 50%;
	}
	.child {
	  position: relative; 
	  left: -50%; 
	}	
</style>
</head>
<body>
    <h2>Align absolute positioned div  </h2>
    <div class="container">
	   <div class="child">
	     <h3>Centered aligned div</h3>
		</div>
    </div>
</body>
</html>

Output

Here is the output of the above program.

center align absolute positioned div

Using margin, left, and right properties

We can also use CSS margin in addition to left and right properties to center align the absolute positioned div. Use margin: auto to set equal width margin to left and right of div.

Example: Center align absolute positioned div using margin, left, and right properties.

In this program, we have used margin:auto, left:0, and right:0 to center align the div.

Conclusion

In this tutorial, we have learned to center align the div element with position: absolute property. We can do so using left properties or combining margin, left, and right properties.



About the author: