问题描述
两个行内块元素具有行内和块级两者的属性,均可设置宽高,并且可以实现两个元素并排显示,期望效果如下
但如果其中一个元素内添加文本内容,那么将会出现两个原本并排显示的元素上下错位,如下
<!-- 问题代码 -->
<style>
.fir,
.sec {
width: 100px;
height: 50px;
margin: 10px;
display: inline-block;
border-radius: 10px;
text-align: center;
color: white;
}
</style>
<body>
<div class="fir" style="background-color: red;">logo</div>
<div class="sec" style="background-color: green;"> </div>
</body>
问题分析
行内块因为文本的添加导致其对齐方式出现了变化,如果另一个元素没有添加文本,那么在对齐上就会错位
解决办法
方式一:
在另一个并排元素处的标签内添加文本内容,如果没有实质内容,可以添加 空格
<!-- 解决办法一:另一个元素内部添加 -->
<style>
.fir,
.sec {
width: 100px;
height: 50px;
margin: 10px;
display: inline-block;
border-radius: 10px;
text-align: center;
color: white;
}
</style>
<body>
<div class="fir" style="background-color: red;">logo</div>
<div class="sec" style="background-color: green;"> </div>
</body>
方式二:overflow
给写入了文本内容的标签,设置 overflow,如果给不含文本标签的设置不起作用,如果是input类标签同样不起作用
<!-- 解决办法二:有文本内容的元素设置overflow -->
<style>
.fir,.sec {
width: 100px;
height: 50px;
margin: 10px;
display: inline-block;
border-radius: 10px;
text-align: center;
color: white;
}
.fir{
overflow: auto;
}
</style>
<body>
<div class="fir" style="background-color: red;">logo</div>
<div class="sec" style="background-color: green;"></div>
</body>
方式三:vertical-align:middle;
不管有没有行内文本,两个都设置其为居中对齐,因此无论是input还是span都可以通过这个方式解决,注意 vertical-align:middle; 只对行内元素(例如,文字、图片等)起作用,如果只设置其中一个也不起作用
<style>
.fir,.sec {
height: 20px;
margin: 10px;
border-radius: 10px;
color: white;
vertical-align: middle;
}
.fir{
width: 100px;
}
.sec{
display: inline-block;
width: 20px;
}
</style>
<body>
<input class="fir" style="background-color: red;">
<div class="sec" style="background-color: green;"></div>
</body>
<style>
.parent,.child,.other {
width: 300px;
height: 250px;
margin: 10px;
display: inline-block;
border-radius: 10px;
text-align: center;
color: white;
vertical-align: middle; /* 三者都是设置为垂直居中,能让其并排显示 */
}
.child{
width: 200px;
height: 150px;
background-color: antiquewhite;
border-radius: 10px;
}
</style>
<body>
<div class="parent" style="background-color: red;">
<div class="child"></div>
</div>
<div class="other" style="background-color: green;"></div>
</body>