1.绝对定位与负边距实现(已知高度宽度)
这种方式需要知道被垂直居中元素的高和宽,才能计算出margin值,兼容所有浏览器
// html部分
<body>
<div id='container'>
<div id='center' style="width: 100px;height: 100px;background-color: #666">center</div>
</div>
</body>
// css部分
#container {
position: relative;
}
#center {
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
2.绝对定位与margin:auto(已知高度宽度)
这种方式无需知道被居中元素的高和宽
#container {
position: relative;
height:100px;//必须有个高度
}
#center {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;//注意此处的写法
}
3.绝对定位+CSS3(未知元素的高度)
利用Css3中的transform,可以轻松的在未知元素的高度的情况下实现元素的垂直居中
#container {
position: relative;
}
#center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4.flex布局
利用flex布局,其中justify-content 用于设置或检索弹性盒子元素在主轴(横轴)方向上的对齐方式;而align-items属性定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。不能兼容低版本的IE浏览器
#container {//直接在父容器设置即可
height: 100vh;//必须有高度
display: flex;
justify-content: center;
align-items: center;
}
5.flex/grid与margin:auto(最简单的写法)
容器元素设置为flex布局或者是grid布局,子元素只要写margin:auto即可
#container {
height: 100vh;//必须有高度
display: grid;
}
#center {
margin: auto;
}
网友评论