我有 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;
}
最佳答案
使用 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/