元素在页面内垂直居中的四种办法
第一种:利用定位
对第一种办法进行细分,可以分为两种第一小种:
设置绝对定位或者固定定位之后,设置left和top的值为50%,然后设置margin-left和margin-right的值为负的元素的半个身位,这样设置的元素就可以在页面内垂直居中了。
html部分:
<div class = "box">这是HTML代码<div>
css部分:
.box{
height:100px;
width:100px;
background-color:red;
position:absolute/fixed;
left:50%;
top:50%;
margin-left:-50px;
margin-top:-50px;
}
第二小种:
设置绝对定位或者固定定位之后,设置margin为0,然后设置上下左右四个方向为0html部分:
<div class = "box">这是HTML代码</div>
css部分:
.box{
height:100px;
width:100px;
background-color:red;
position:absolute/fixed;
margin:0;
top:0;
left:0;
right:0;
bottom:0;
}
第二种:利用伪元素
利用伪元素将屏幕高度撑开,然后可以利用vertica—align:middle属性将元素置于页面居中位置
html部分:
<div id = "box">
<span class = "assist"></span>
<div class = "main"></div>
</div>
css部分:
body {
margin: 0;
height: 100%;
background-color: aliceblue1;
}
#box {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
text-align: center;
font-size: 0;
}
.assist {
vertical-align: middle;
display: inline-block;
height: 100%;
width: 1px;
margin-left: -1px;
}
.main {
vertical-align: middle;
display: inline-block;
width: 100px;
height: 100px;
background-color: red;
}
这个方法也可以说是利用了vertic-align这个属性,实现了居中。具体是如何利用vertical-align:middle;请参考博客园
,这篇文章中有详解。
第三种,利用元素撑开屏幕高度,与伪元素有稍雷同,原理一致
html部分:
<div class = "nav"></div>
<div class = "box"></div>
css部分:
*{
padding:0;
margin:0;
}
html{
height:100%;
width:100%;
}
body{
width:100%;
height:100%;
text-align:center;
}
.nav{
height:100%;
display:inline-block;
vertical-align:middle;
}
.box{
width:400px;
hieght:100px;
background-color:red;
display:inline-block;
vertical-align:middle;
}
同样是vertical-align:middle的应用。
第四种办法:css3的flex应用
html部分:
<divid="box">
</div>
css部分:
*{
padding: 0;
margin: 0;
}
body,html{
width: 100%;
height: 100%;
}
body{
display: flex;
justify-content: center;
align-items: center;
}
#box{
width: 400px;
height: 300px;
background: pink;
}
这四种常见的办法可以解决元素在页面内垂直水平居中的需求,暂时无解析,后续会更新。