垂直对齐不按预期工作

时间:2016-03-04 10:16:10

标签: css

当我试图更熟悉baseline属性时,我遇到了一个问题。该属性的默认值为h2,它将元素的基线与其父级的基线对齐。我将代码显示底部的inline-block元素设为body,以了解它的行为方式以及当我感到惊讶时的行为。它不应该显示在身体边界的正上方,就像蓝色框显示的那样,而不是在身体中心的某个地方吗?看起来像对齐这些框(div)会垂直影响<!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>的基线所在的位置,但为什么呢?请点击&#34;整页&#34;在运行代码段以查看行为时。

&#13;
&#13;
h2
&#13;
&#13;
&#13;

我预计{{1}}会下降,如下图所示。 enter image description here

3 个答案:

答案 0 :(得分:2)

元素以这种方式对齐,因为baseline将其与父元素内文本的基线对齐。
在您的情况下,文本基线被大inline-block div下推。 h2与此文本一致。如果您希望它与其他内联元素的底部对齐(如图所示),请将样式vertical-align: bottom添加到您的h2。

本文非常好地解释了不同的垂直对齐值:
https://css-tricks.com/what-is-vertical-align/

答案 1 :(得分:1)

我强烈建议您阅读这篇vertical-align文章,以深入了解该属性。

答案 2 :(得分:-1)

当你使用内联块时,最好通过定位它们来处理你的元素。看看我对h2的css风格的变化。

&#13;
&#13;
<!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: 100px;
			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;
                  width:300px;
                  size:10px;
                  vertical-align:bottom;
                 }
	</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>
&#13;
&#13;
&#13;