How to Horizontally Center a <div> in Another <div>

The HTML <div> tag is used to define parts of a page or a document. It groups large sections of HTML elements and styles them with CSS.

If you want to put a <div> element in the center of another <div>, use CSS styles to position it exactly at the center of another <div> horizontally. Follow the steps below and get the code snippet.

Create HTML

  • Create two <div> elements with "id" attributes named "outer-div" and "inner-div". Place the second <div> within the first one.
<div id="outer-div">
  <div id="inner-div">I am a horizontally centered div.</div>
</div>

Add CSS

  • Set the width of the outer element (i.e. 100% covers the whole line). Change it according to your requirements.
  • Set the margin property to "auto" to horizontally center the <div> element within the page. The "margin: 0 auto" does the actual centering.
  • Set your preferred colors for the outer and inner <div> elements by using the background-color property.
  • Use the "inline-block" value of the display property to display the inner <div> as an inline element as well as a block.
  • Set the text-align property on the outer <div> element to center the inner one. This property only works on inline elements.
#outer-div {
  width: 100%;
  text-align: center;
  background-color: #0666a3
}

#inner-div {
  display: inline-block;
  margin: 0 auto;
  padding: 3px;
  background-color: #8ebf42
}

Here is the full code.

Example of horizontally centering a <div> element within another one with the text-align property:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #outer-div {
        width: 100%;
        text-align: center;
        background-color: #0666a3
      }
      #inner-div {
        display: inline-block;
        margin: 0 auto;
        padding: 3px;
        background-color: #8ebf42
      }
    </style>
  </head>
  <body>
    <div id="outer-div">
      <div id="inner-div"> I am a horizontally centered div.</div>
    </div>
  </body>
</html>
Set also padding to create space around the inner element.

Example of horizontally centering a <div> element within another one with the display property:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #main-container {
        display: flex;
        width: 100%;
        justify-content: center;
        background-color: #0666a3;
      }
      #main-container div {
        background-color: #8ebf42;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <div id="main-container">
      <div> I am a horizontally centered div with the CSS display property.</div>
    </div>
  </body>
</html>

Do you find this helpful?

Related articles