Colin Aulds Colin Aulds - 11 days ago 5
React JSX Question

horizontally centering three h2's

I'm struggling to horizontally center three

<h2>
elements



#container {
margin: 0 auto;
width: 100%;
height: 3em;
}

h2 {
display: inline-block;
text-align: center;
width: 33%;
margin-left: auto;
margin-right:auto;
border-radius: 5px;
font-family: Arial;
color: Black;
font-size: 18px;
background: #FDF3E7;
padding: 10px 20px 10px 20px;
border: solid #7E8F7C 3px;
}

<div id="container">
<h2 class="header">Restaunt Name:</h2
><h2 class="header">Phone #:</h2
><h2 class="header">Star Rating:</h2>
</div>





I tried removing the white space by reformatting the HTML. I also tried using this site. I can't get the third element to sit inside the container.

Update: I followed jcuenod's advice. This seems to have solved the block level question of horizontal centering, but looking at the styling, I am now wondering why the headers are matching with their results. Here is what they look like now.

enter image description here

Shouldn't the h2's occupy the entirety of the container, given that they are centered across a container with 100% width?

Answer

The Problem

The problem is that you have widths that fill the horizontal space (mostly; 33%). But then your <h2> elements take up extra horizontal space because you add padding and border.

The Solution

Use box-sizing as follows:

box-sizing: border-box;

Explanation

MDN explains the border-box setting for box-sizing:

The width and height properties include the content, the padding and border, but not the margin.

MDN lists it as experimental but it has very good browser support.

#container {
  width: 100%;
  height: 3em;
}
h2 {
  box-sizing: border-box;
  display: inline-block;
  text-align: center;
  width: 33%;
  -webkit-border-radius: 5;
  -moz-border-radius: 5;
  border-radius: 5px;
  font-family: Arial;
  color: Black;
  font-size: 18px;
  background: #FDF3E7;
  padding: 10px 20px 10px 20px;
  border: solid #7E8F7C 3px;
}
<div id="container">
  <h2 class="header">Restaunt Name:</h2
  ><h2 class="header">Phone #:</h2
  ><h2 class="header">Star Rating:</h2>
</div>

Comments