水平居中三个h2&#39

时间:2016-11-22 04:35:24

标签: html css reactjs

我正在努力横向居中三个<h2>元素

&#13;
&#13;
#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;
}
&#13;
        <div id="container">
          <h2 class="header">Restaunt Name:</h2
          ><h2 class="header">Phone #:</h2
          ><h2 class="header">Star Rating:</h2>
        </div>
&#13;
&#13;
&#13;

我尝试通过重新格式化HTML来删除空白区域。我也尝试过使用this site。我无法将第三个元素放在容器内。

更新:我遵循了jcuenod的建议。这似乎已经解决了水平居中的块级问题,但是看看样式,我现在想知道为什么标题与它们的结果匹配。这是他们现在的样子。

enter image description here

如果h2占据了整个容器,假设它们居中于100%宽度的容器中?

4 个答案:

答案 0 :(得分:2)

问题

问题是你有宽度填充水平空间(主要是33%)。但是,由于您添加了<h2>padding,因此border元素会占用额外的水平空间。

解决方案

使用box-sizing,如下所示:

box-sizing: border-box;

解释

MDN解释了border-box的{​​{1}}设置:

  

宽度和高度属性包括内容,填充和边框,但不包括边距。

MDN将其列为实验性的,但它有very good browser support

&#13;
&#13;
box-sizing
&#13;
#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;
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

只需将display: block用于<h2>

答案 2 :(得分:0)

text-align:center;添加到#container元素。

由于您的h2元素设置为inline-block,因此它们不占用其容器的整个宽度。这就是为什么定心不起作用的原因。

答案 3 :(得分:0)

如果您需要同一行上的每个元素:

#container {
  margin: 0 ! important;
  padding : 0 ! important;
  width: 100%;
  height: 3em;
  text-align:center;
}

h2 {

  display: inline-block;
  text-align: center;
  width: 33%;
  /*margin-left: auto;
  margin-right:auto;*/
  -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;
}
<form id="form" onSubmit={this.getRecommendations} type="text">
          <input id="zipInput" type="text" placeholder="Zip Code or City" ref="zip"/>
          <input id="kindInput" type="text" placeholder="Food Type" ref="kind"/>
          <button id="button" type="submit">Get Results!</button>
        </form>
        <div id="container">
          <h2 class="header">Restaunt Name:</h2>     
          <h2 class="header">Phone #:</h2>
          <h2 class="header">Star Rating:</h2>
        </div>

相关问题