此代码显示了以css垂直居中的多行。如果显示不是内联块,为什么行高:1.5不起作用?
<!DOCTYPE html>
<html>
<head>
<style>
.center {
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
}
.center p {
line-height: 1.5;
display: inline-block;
vertical-align: middle;
}
</style>
</head>
<body>
<h2>Centering</h2>
<p>In this example, we use the line-height property with a value that is equal to the height property to center the div element:</p>
<div class="center">
<p>I am vertically and horizontally centered.</p>
</div>
</body>
</html>
w3schools 中的代码链接
因为默认情况下p
是一个块元素,所以用于在行框内居中内联内容的line-height:200px
将没有效果,因为我们没有行框也没有内联内容。
通过制作pinline-block
,您创建了内联内容,line-height
就会罢工。
或者,您可以保留块默认显示,并删除p
内的线高度,这样它将继承200px
,居中将应用于p
:内
<!DOCTYPE html>
<html>
<head>
<style>
.center {
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
}
.center p {
margin:0;
}
</style>
</head>
<body>
<h2>Centering</h2>
<p>In this example, we use the line-height property with a value that is equal to the height property to center the div element:</p>
<div class="center">
<p>I am vertically and horizontally centered.</p>
</div>
</body>
</html>
在内容由内联级元素组成的块容器元素上ref
如果没有inline-block
,就没有内联级别元素