wss小弟总结的css 垂直居中方法
margin:auto(position:absolute)
margin:0 auto;能实现水平居中,为什么margin:auto;为什么不能实现垂直居中,换句话来说margin:auto 0; 为什么不能实现效果。
引用自
auto的作用为:自动填充剩余空间
块级元素在水平方向自动填充一整行,而在垂直方向上不会自动填充
所以给块级元素设置margin:auto时,块级元素在水平方向上,左右的margin平分剩余空间,在垂直方向上,没有剩余空间可平分,所以呈现只有水平居中的效果。
abosolue拉伸爆炸效果实现居中(折翼天使)
absolute之后自动去获取边界
<div class="content">
</div>
.content{
top: 0;
bottom: 0;
right: 0;
left: 0;
width: 300px;
height: 300px;
background: orange;
position: absolute;
margin: auto;
}
margin:auto(父元素display:flex;)
其实这个写法和上面一个类似,都属于脱离文档流之后指定上下边界,使auto自动垂直居中
来自chococo女神小姐姐
简单翻译一下,大意是在 flex 格式化上下文中,设置了 margin: auto 的元素,在通过 justify-content 和 align-self 进行对齐之前,任何正处于空闲的空间都会分配到该方向的自动 margin 中去
这里,很重要的一点是,margin auto 的生效不仅是水平方向,垂直方向也会自动去分配这个剩余空间。
<body>
<div class="content">
</div>
</body>
body{
display: flex;
height: 100vh;
}
.content{
width: 300px;
height: 300px;
background: orange;
margin: auto;
}
position:relative; top:50%;margin-top:负一半高度(或者transform: translateY(-50%))
通过relative 获取高度边界,再通过margin-top:微调居中。
<body>
<div class="content">
</div>
</body>
body{
height: 100vh;
}
.content{
width: 300px;
height: 300px;
background: orange;
margin: auto;
position: relative;
top: 50%;
margin-top: -150px;
/*css3属性*/
/*transform: translateY(-50%);*/
}
display:flex;align-items:center;justify-content:center;
需要指定父元素高度
100vh
子元素按照flex布局居中
<body>
<div class="content">
</div>
</body>
body{
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.content{
width: 300px;
height: 300px;
background: orange;
}
看来最牛的还是 absolute 不需要设置父级高度
张鑫旭大哥的垂直居中效果实现
== 我的理解 ==
张鑫旭大哥这一手垂直居中,看懂之后其实也是很巧妙的,也能看出张大哥对inlin-block理解的深入,主要应用的是inline-black 的baseline在中线,所以当高度扩大到100%的时候;我推测会影响旁边元素的baseline 从而形成垂直居中的效果, 元素特性。text-align控制居中,通过居中元素左右一项元素扩大行高度,vertical-align: middle;控制居中。
张鑫旭大哥版本
<div class="container">
<div class="dialog">
</div>
</div>
.container {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0,0,0,.5);
text-align: center;
font-size: 0;
white-space: nowrap;
overflow: auto;
}
.container:after {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.dialog {
display: inline-block;
vertical-align: middle;
text-align: left;
font-size: 14px;
white-space: normal;
}
小弟我理解之后的版本
<body>
<div class="aftercontent">
2222
</div>
<div class="content">
11111
</div>
<!--
<div class="aftercontent">
2222
</div>
前后皆可
-->
</body>
body{
/*控制水平居中*/
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
text-align: center;
background-color: rgba(0,0,0,.5);
}
.aftercontent{
/*控制垂直居中*/
content: '';
display: inline-block;
height: 100vh;
vertical-align: middle;
background-color: red;
width: 10px;
}
.content{
vertical-align: middle;
display: inline-block;
background: orange;
}
== 会继续更新==