当我试图更熟悉 vertical-align
属性时,我遇到了一个问题。该属性的默认值为baseline
,它将元素的基线与其父元素的基线对齐。我将代码底部的 h2
元素显示为 inline-block
来查看它的行为方式,这让我感到惊讶。它不应该像蓝色框一样显示在 body 边框的正上方,而不是在 body 中心的某个地方吗?看起来垂直对齐这些框(div)会影响 body
的基线位置,但为什么呢?请在运行代码片段时单击“完整页面”以查看行为。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vertical align</title>
<style>
body {border: 1px solid black; line-height: 1;}
.box {
display: inline-block;
width: 150px;
vertical-align: middle;
}
.tall {
height: 300px;
background-color: lightblue;
}
.short {
height: 100px;
background-color: green;
}
.middle {
height: 200px;
background-color: yellow;
}
.square {
display: inline-block;
width: 5px;
height: 5px;
background-color: red;
vertical-align: middle;
}
h2 {display: inline-block;}
</style>
</head>
<body>
<h1>Vertical Align</h1>
<div class="box tall"></div>
<div class="box short"></div>
<div class="box middle"></div>
<h2>Picture aligned <div class="square"></div> within text</h2>
</body>
</html>
最佳答案
我强烈推荐阅读这篇文章 vertical-align文章以深入了解该属性。
关于css - 垂直对齐未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35793380/