<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
html,body{
width: 100%;
height: 100%;
}
#box{
width: 50%;
height: 50%;
background: paleturquoise;
text-align: center;
line-height: 50%
}
</style>
<body>
<div id="box">
hehe
</div>
</body>
</html>
这个问题我之前也遇到过。发现用line-height设置百分比,实际上这个百分比是根据字体大小计算的。
后来我通过增加一个父元素。父元素设置display:table
需要居中的元素 设置
vertical-align:middle;
display:table-cell;
期待更佳方案
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
html,body{
width: 100%;
height: 100%;
}
#box{
width: 50%;
height: 50%;
background: paleturquoise;
text-align: center;
display:table;
}
.tab{ display:table-cell;
vertical-align:middle;
}
</style>
<body>
<div id="box">
<div class="tab">hehe</div>
</div>
</body>
</html>
display: flex;
justify-content: center;
align-items: center;
1,line-height
的百分比是相对font-size
的,所以你如果需要使用line-height
居中的话就使用绝对的px
值。
2,当然有其他方案,比如楼上的方案,还有css3的新特性,还有提前知道高度,把line-height
设置为对应的高度就可以
display:flex;
align-items:center;
justify-content:center;