<p>中的换行文本会改变</p> <div>的位置

时间:2017-06-02 18:24:44

标签: html css

我有4个div s具有明确的高度&amp; widths,每个包含一个p元素。在一种情况下,文本从一个p换行到第二行。这会改变div的位置。开发工具不会显示父级div或其位置移动的div的边距或填充的任何更改。

这是我的HTML:

<div id="holder">
  <div class="box"><p>I got words</p></div>
  <div class="box"><p>I got words too</p></div>
  <div class="box"><p>I got no words</p></div>
  <div class="box"><p>I got so many words that they wrap down</p></div>
</div>

这是我的CSS:

#holder {
  width: 100%;
  background: rgba(25, 25, 25, 0.9);
  text-align: center;
}

.box {
  height: 100px;
  width: 150px;
  background-color: green;
  display: inline-block;
}

这里是笔的链接:https://codepen.io/Yeti_Detective/pen/rwNVXV

3 个答案:

答案 0 :(得分:1)

使用display:inline-block时,您需要注意vertical-align:baseline - 默认值 - 仍然有效。

这意味着内联块元素根据文本基线对齐,在双线元素的情况下根据底线。

&#13;
&#13;
#holder {
  width: 100%;
  background: rgba(25, 25, 25, 0.9);
  text-align: center;
}

.box {
  height: 100px;
  width: 150px;
  background-color: green;
  display: inline-block;
}

#marker {
  position: absolute;
  width: 304px;
  margin-top: -1em;
  border-top: 1px solid white;
}
&#13;
<div id="holder">
  <div class="box"><p>I got words</p><div id="marker"></div></div>
  <div class="box"><p>I got so many words that they wrap down</p></div>
</div>
&#13;
&#13;
&#13;

有两种方法可以解决这个问题。选项1是将vertical-align:top添加到框中。这将完全符合它的说法。

我个人更喜欢的选项2是在容器上使用display:flex。您需要justify-content: center对齐方框。

&#13;
&#13;
#holder {
  width: 100%;
  background: rgba(25, 25, 25, 0.9);
  text-align: center;
  display: flex;
  justify-content: center;
}

.box {
  height: 100px;
  width: 150px;
  margin: 0 4px;
  background-color: green;
}
&#13;
<div id="holder">
  <div class="box"><p>I got words</p></div>
  <div class="box"><p>I got words too</p></div>
  <div class="box"><p>I got no words</p></div>
  <div class="box"><p>I got so many words that they wrap down</p></div>
</div>
&#13;
&#13;
&#13;

完成:)

答案 1 :(得分:0)

您错过了vertical-align:top;属性这是小提琴https://jsfiddle.net/28afvwbd/1/

CSS代码

#holder {
  width: 100%;
  background: rgba(25, 25, 25, 0.9);
  text-align: center;
}

.box {
  height: 100px;
  width: 150px;
  background-color: green;
  display: inline-block;
  vertical-align:top;
}

答案 2 :(得分:0)

赋予.box样式vertical-align: top;应该可以解决问题。

&#13;
&#13;
#holder {
  width: 100%;
  background: rgba(25, 25, 25, 0.9);
  text-align: center;
}

.box {
  height: 100px;
  width: 150px;
  background-color: green;
  display: inline-block;
  vertical-align: top;
}
&#13;
<div id="holder">
  <div class="box"><p>I got words</p></div>
  <div class="box"><p>I got words too</p></div>
  <div class="box"><p>I got no words</p></div>
  <div class="box"><p>I got a lot of words, but I no longer wrap down!</p></div>
</div>
&#13;
&#13;
&#13;