1.水平居中
(1)代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.container{
width: 400px;
height: 300px;
background-color: lightblue;
}
.item{
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="item">水平居中</div>
</div>
</body>
</html>
*备注:关键代码
(2)运行效果
2.垂直居中
(1)代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.container{
width: 400px;
height: 300px;
background-color: lightblue;
}
.item{
text-align: center;
line-height: 300px;
}
</style>
</head>
<body>
<div class="container">
<div class="item">水平居中+垂直居中</div>
</div>
</body>
</html>
(2)运行示例
*关键的两行代码: line-height: 300px; height: 300px;
使line-height与行高一致,即可实现垂直(竖直)居中。