总结记录一下常常须要用到垂直居中布局,欢迎补充(空手套。。。O(∩_∩)O)css
如下栗子若是未特别标注同一使用这样的html结构html
<div class="container">
<div class="content"></div>
</div>
复制代码
绝对定位能够很容易作到top:50%,如今只要再让目标元素上移自身高度的一半就垂直居中了css3
.container {
background: #777777;
height: 400px;
position: relative;
}
.container .content {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
margin-top: -50px;
left: 50%;
margin-left: -50px;
background: #ee5f28;
}
复制代码
优势:兼容性好 缺点:须要知道居中元素的高度浏览器
.container {
background: #777777;
height: 400px;
position: relative;
}
.container .content {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0);
background: #ee5f28;
}
复制代码
.container {
background: #777777;
height: 400px;
position: relative;
}
.container .content {
width: 100px;
height: 100px;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
background: #ee5f28;
}
复制代码
.container {
background: #777777;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
.container .content {
width: 100px;
height: 100px;
background: #ee5f28;
}
复制代码
.container {
background: #777777;
height: 400px;
display: flex;
}
.container .content {
width: 100px;
height: 100px;
background: #ee5f28;
margin: auto;
}
复制代码
.container {
background: #777777;
height: 400px;
position: relative;
}
.container .content {
width: 100px;
height: 100px;
background: #ee5f28;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
复制代码
优势:布局
.container {
background: #777777;
height: 400px;
text-align: center;
font-size: 0;
overflow: auto;
}
.container::after {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.container .content {
display: inline-block;
vertical-align: middle;
width: 100px;
height: 100px;
background: #ee5f28;
}
复制代码
这里注意
:容器‘container’里要设置font-size:0;避免inline-block之间产生间隔测试
优势:flex
<!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> .container-table { background: #777777; height: 400px; width: 100%; display: table; } .container-table .container-cell { display: table-cell; vertical-align: middle;/* 这里达到了垂直居中的效果 */ } .container-table .container-cell .content { width: 100px; height: 100px; margin: 0 auto;/* 利用margin值 水平居中*/ background: #ee5f28; } </style>
</head>
<body>
<div class="container-table">
<div class="container-cell">
<div class="content"></div>
</div>
</div>
</body>
</html>
复制代码