How to align a DIV horizontally center using CSS

Topic: HTML / CSS« Prev|Next »

Answer: Set the style rule "margin:0 auto;" for DIV

If you would like to align the <div> element horizontally center with respect to the parent element you can use the CSS margin property.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>Center Align Div Using CSS</title>
  • <style type="text/css">
  •     .container {
  •         width: 80%;
  •         margin: 0 auto;
  •         padding: 20px;
  •         background: #f0e68c;
  •     }
  • </style>
  • </head>
  • <body>
  •     <div class="container">
  •         <h1>This is a heading</h1>
  •         <p>This is a paragraph.</p>
  •     </div>
  • </body>
  • </html>

As you can see we have applied the auto value to the left and right margin property of the <div> element. The auto value automatically adjust the left and right margin and align the div box horizontally center.


Note:The above solution works only when the width of parent element is more the containing <div> element that you want to align.


Your Feedback:


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