How to center align absolute positioned div using CSS

Topic: HTML / CSS« Prev|Next »

Answer: Use the CSS margin, left, right Property

You can align any absolutely or fixed positioned <div> element horizontally center using the CSS margin property in combination with the left and right position property.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>Center Alignment of Absolutely Positioned Elements</title>
  • <style type="text/css">
  •     .box {
  •         width: 50%;
  •         position: absolute;
  •         z-index: 99;
  •         margin: 0 auto;
  •         left: 0;
  •         right: 0;
  •         padding: 20px;
  •         background: #f0e68c;
  •     }
  • </style>
  • </head>
  • <body>
  •     <div class="box">
  •         <h1>This is a heading</h1>
  •         <p>This is a paragraph.</p>
  •     </div>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.