WebMasterCampus
WEB DEVELOPER Resources

How to Horizontally Center a Div Element

How can horizontally center a child/inner div element inside a parent div element using CSS?


Horizontally Center a Div Element

We can achieve this by using applying display: table or display: inline-block in inner <div> element.

Horizontal Center using CSS display table

display tables means elements behave like HTML <table> elements. It defines a block-level box.

#outer {  
  border: 1px solid red;
  
}
#inner {
  display: table;
  margin: 0 auto;
  border: 1px solid;
}

Horizontal Center child <div> using display: inline-block

We need to use display: inline-block in child <div> element and use text-align: center into parent <div> element.

#outer {
  
  border: 1px solid red;  
  text-align: center;
}

#inner {  
  border: 1px solid;
  display: inline-block;  
}

We can also use flexbox. It is widely supported by all current major browsers. The container needs to be specified as a flex container, along its main content to center.

#container {
  display: flex;
  justify-content: center;
  align-items: center;
}

#flex{
  flex 0 0 100px;
}

Learn more about CSS display

Created with love and passion.