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

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

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

1. Create HTML

  • Create two <div> elements with IDs "outer-div" and "inner-div".
  • Specify the width of the "outer-div" class.
<div id ="outer-div" width="100%">
<div id ="inner-div"> I am a horizontally centered div.</div>

2. Create CSS

Let’s see centering a <div> in a <div> horizontally step by step:

  • Set the width of the outer element (i.e 100% covers the whole line). Change it according to what size you need.
  • Set the margin property to auto to horizontally center the <div> element within the page. The "margin: 0 auto" is what does the actual centering.
  • Set your preferred colors for outer and inner divs using the background-color property.
  • Use "inline-block" which is a value of display property and displays the inner div as an inline element as well as a block.
  • Set the text-align property in the outer div to center the inner div. Remember that 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 a horizontally centered div:

<!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" width="100%">
    <div id ="inner-div"> I am a horizontally centered div.</div>
    <div>
  </body>
</html>

Set also padding in order to create space around your inner element.


Do you find this helpful?

Related articles