css - 垂直对齐未按预期工作

标签 css

当我试图更熟悉 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>

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

最佳答案

我强烈推荐阅读这篇文章 vertical-align文章以深入了解该属性。

关于css - 垂直对齐未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35793380/

相关文章:

css - Bootstrap 模态背景不会消失

css - 带有填充的 div 内的 Internet Explorer 边距问题

html - 在 div 元素中右对齐内容

css - 当左侧有很多内容时,防止 CSS 将节点包裹在其最大宽度以下的树中,例如思维导图

javascript - 如何限制 1 div 与另一个 div 的距离不超过一定长度?

html - Internet Explorer 8 及以下版本的显示样式

css - 哪些 CSS 属性进入 Id,哪些进入 class

javascript - 让我的弹出窗口可以拖动到任何地方?

html - 图像未 overflow hidden :hidden

html - 无法让图像跟随同一 div 中的文本