元素水平垂直居中那些事

元素在页面内垂直居中的四种办法

第一种:利用定位

对第一种办法进行细分,可以分为两种

第一小种:

设置绝对定位或者固定定位之后,设置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,然后设置上下左右四个方向为0
html部分:
<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;
     }

这四种常见的办法可以解决元素在页面内垂直水平居中的需求,暂时无解析,后续会更新。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

summer·

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值