一.常用方式
让文字水平垂直居中通常使用的方法是:text-align: center(水平居中);line-height: 20px(垂直居中);值得注意的是line-height的值必须是固定值,即该元素的高度必须固定。
二.引出问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
*{
width: 100%;
height: 100%;
}
.box{
width: 40%;
height: 30%;
font-size: 24px;
background: red;
text-align: center;
line-height: 100%; (注意)
}
</style>
<body>
<div class="box">
快让我水平垂直居中!!!
</div>
</body>
</html>
复制代码
效果图:
设置line-height是没用的。三.决解方案
- 利用弹性布局
- 利用display:table-cell