Horizontal align CSS | How to Horizontally center a

Horizontal align CSS

To Center Align Elements in HTML (like), use CSS code margin: auto;. Try to set the width of elements, it will prevent them from stretching out to the edges of its container.

You can do align div, text, image elements by suing CSS.

Horizontally Center Align Text

To just center the text inside an element, use text-align: center; it will center text vertically and horizontally.

<!DOCTYPE html>
<html>
<head>
    <style>
        .div1 {
          text-align: center;
          border: 3px solid red;
      }
  </style>
</head>
<body>

    <div class="div1">
      <p>CENTER TEXT</p>
  </div>

</body>
</html>

Output:

CSS Horizontally Center Align Text

How to horizontally center a <div>

Example of How to horizontally center a <div> within another <div> using CSS:-

Apply this CSS to the inner <div>, It will make the inner element center horizontally.

#inner {
  width: 50%;
  margin: 0 auto;
}
Complete example code
<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        #inner {
          display: table;
          margin: 0 auto;
          border: 1px solid black;
      }

      #outer {
          border: 1px solid red;
          width:100%
      }
  </style>

</head>
<body>


   <div id="outer">
      <div id="inner">Foo foo</div>
  </div>
</div>


</body>
</html>

Output:

horizontally center div html

Do comment if you have any doubts and suggestion on this topic.

Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.