我有4个div
s具有明确的高度& 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;
}
答案 0 :(得分:1)
使用display:inline-block
时,您需要注意vertical-align:baseline
- 默认值 - 仍然有效。
这意味着内联块元素根据文本基线对齐,在双线元素的情况下根据底线。
#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;
有两种方法可以解决这个问题。选项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;
}
&#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;
完成:)
答案 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;
应该可以解决问题。
#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;