css居中的几种实现方式

1.?使用padding
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.wrap {
width: 300px;
background-color: pink;
padding: 100px 0;
text-align: center;
}
</style>
</head>
<body>
<div class="wrap">
使用padding让文本垂直居中显示
</div>
</body>
</html>
2.?使用绝对定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.wrap {
width: 300px;
height: 300px;
line-height: 300px;
text-align: center;
background-color: red;
color: #fff;
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -150px;
}
</style>
</head>
<body>
<div class="wrap">
使用绝对定位让.wrap垂直居中显示
</div>
</body>
</html>
3.?使用CSS3 transform
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.wrap {
width: 300px;
height: 300px;
line-height: 300px;
text-align: center;
background-color: red;
color: #fff;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="wrap">
使用CSS3 transform让 .wrap垂直居中显示
</div>
</body>
</html>
4.?使用伪元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.wrap {
width: 400px;
height: 300px;
margin: 0 auto;
background-color: #ccc;
text-align: center;
}
.wrap::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="wrap">
使用伪元素实现垂直居中
</div>
</body>
</html>

0 个评论

要回复文章请先登录注册