html - <p> 中的换行文本更改 <div> 位置

标签 html css

我有 4 个定义了高度和宽度的 div,每个包含一个 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

最佳答案

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

这意味着行内 block 元素根据文本基线对齐,在两行元素的情况下是根据底线对齐。

#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;
}
<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>

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

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

#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;
}
<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>

完成:)

关于html - <p> 中的换行文本更改 <div> 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335281/

相关文章:

html - CSS:单击时列内的链接移动

javascript - 如何让我的图像在 HTML 或 CSS 中的某个点停止重复?

复选框的 CSS 在 IE 中不起作用

javascript - 滚动然后捕捉到顶部而不是取消捕捉

javascript - react css 优先级

html - 如何让 flex 中的 child 全宽?

javascript - 如何用单词隐藏整行文本

html - CSS 样式表未链接到 html

html - 如何在css中使图像全屏显示?

jquery - bootstrap-maxlength 总是在最前面