1、relative+absolute定位:
(1)css+html代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.parent {
width: 400px;
height: 400px;
margin: 100px;
border: 1px solid red;
position: relative;
}
.child {
width: 200px;
height: 200px;
border: 1px solid green;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="parent">
父元素
<div class="child">
子元素
</div>
</div>
</body>
</html>
(2)效果
Paste_Image.png
(3)兼容性:兼容全部浏览器
2、flex布局:
(1)html+css代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.parent {
width: 400px;
height: 400px;
margin: 100px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child {
width: 200px;
height: 200px;
border: 1px solid green;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
子元素
</div>
</div>
</body>
</html>
(2)效果
Paste_Image.png
(3)兼容性
Paste_Image.png3、relative+transform定位:
(1)html+css代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.parent {
width: 400px;
height: 400px;
margin: 100px;
border: 1px solid red;
}
.child {
width: 200px;
height: 200px;
border: 1px solid green;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
子元素
</div>
</div>
</body>
</html>
(2)效果
Paste_Image.png
(3)兼容性
Paste_Image.png
总结:
根据项目浏览器兼容性要求,选择合适的垂直居中的方案。方案2和方案3适合用在移动端项目,方案1兼容性方面最好。
作者:王翔 QQ:592767079 Email:wangxianglengye.com 期待共同进步!
网友评论