<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>垂直居中</title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
body {
background: red;
}
/*
第一种:
利用calc计算
.box {
width: 900px;
height: 900px;
line-height: 900px;
text-align: center;
background: red;
position: absolute;
top: calc(50% - 300px);
left: calc(50% - 300px);
}
*/
/*
第二种:
在ie9及以下不起作用
transform
.box {
width: 800px;
height: 800px;
line-height: 800px;
text-align: center;
background: orange;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
*/
/*
第三种:
使用视口单位vw和vh
1vw、1vh是与视口相关
1vw是与视口,1vw = 视口宽度的1%
1vh = 视口高度的1%
.box {
text-align: center;
background: yellow;
width: 700px;
height: 700px;
line-height: 700px;
padding: 1em 1.5em;
margin: 50vh auto 0;
transform: translateY(-50%);
}
*/
/*
第四种:
flex的解决方案
body {
display: flex;
min-height: 100vh;
margin: 0;
}
.box {
width: 600px;
height: 600px;
background: green;
line-height: 600px;
text-align: center;
margin: auto;
}
*/
/*
第五种:
万能居中
使用margin和绝对定位
*/
.box {
width: 500px;
height: 500px;
line-height: 500px;
text-align: center;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
background: purple;
}
</style>
</head>
<body>
<div class="box">
水平垂直居中
</div>
</body>
</html>
css水平垂直居中
最新推荐文章于 2023-09-30 13:11:25 发布