line-height不能居中的問題
阿新 • • 發佈:2019-01-30
不居中的情況:
<style>
.ad{
height:40px;
width:500px;
background: red;
float:left;//父級浮動
}
.ex{
font-family: '微軟雅黑';
font-size: 10px;
line-height: 40px;
}
</style>
<body>
<div class='ad'>
<h2 class='ex'>父級浮動,且子元素為塊級元素</h2>
</div>
</body>
居中:
<style>
.ad{
height:40px;
width:500px;
background: red;
float:left;//父級浮動
}
.ex{
font-family: '微軟雅黑';
font-size: 10px;
line-height: 40px;
display:inline;//設為行內元素
}
</style>
<body>
<div class='ad'>
<h2 class='ex'>父級浮動,且只有當子元素為行內元素</h2 >
</div>
</body>
總結:上面兩個例子證明,在父級浮動之後使用line-height,子標籤需要使用行內元素(內聯元素也不可以)才能達到居中要求。