1.方法一:使用绝对定位和transform
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.wrapper {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
text-align: center;
}
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box">盒子</div>
</div>
</body>
</html>
2.使用 display 和 vertical-align 对容器里的文字进行垂直居中
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.wrapper {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
text-align: center;
display: table;
}
.box {
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box">盒子</div>
</div>
</body>
</html>
3.使用弹性布局的方式
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.wrapper {
width: 500px;
height: 500px;
background-color: pink;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="box">盒子</div>
</div>
</body>
</html>
网友评论