div垂直居中的方法

在我们排版的过程当中,有许多样式要求我们把div设置成为垂直居中但有些小伙伴不知道怎么做,
下面就跟着博主来实现如何让div垂直居中,可用一下几种方法 

1.img的垂直水平居中

 <div class="main0">
        <span>111</span>
 </div>

 <style>
    .main0{
        width: 300px;
        height: 300px;
        background-color: #ccc;
        display: table; /* 父元素设置表格属性 */
        text-align: center;
    }
    .main0 span{
        display: table-cell; /* img设置成表格元素属性 */
        vertical-align: middle;/* 两个display设置后这个属性就起作用 */
    }
 </style>

注:  1.1 dispaly:table-cell,这是对类似文字元素起作用的,所以包含在span标签内 
       1.2 对于文字居中h1,span,p等类似文字标签都可以这样设置居中 

2. div的垂直水平居中

 <div class="main1">
     <div class="child"></div>
 </div>

 <style>
    .main1{
            width: 300px;
            height: 300px;
            background-color: hotpink;
            position: relative;
            left: 310px;
            top: -300px;
        }
        .child{
            width: 150px;
            height: 150px;
            background-color: rgba(39, 40, 34, 0.296);
            position: absolute;
            margin: auto;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
        }
 </style>

注: 以上方法同样适用于img, 只需将child换成img就行,不在需要上面方法中的span标签

3.简便实现大部分元素的垂直居中

<div class="main2"></div>

<style>
    .main2{
        display: flex;
        align-items: center;
    }
</style>

注: 3.1  display:flex,将对象作为弹性伸缩盒显示

     3.2 align-items定义flex子项在flex容器的当前行的侧轴方向上的对齐方式

4. 使用css3属性transform

transform: translateY(50%)  给子元素设置垂直居中

5. 单行文本的垂直居中 设置文字的line-height==>父元素的height
<div class="block">单行文本垂直居中</div>

<style>
    .block{
        height: 80px;
        background-color: burlywood;
        line-height: 80px;  /* 值与父元素高度相等 */
        text-align: center;
    }
</style>
6.需要知道子元素的尺寸
<style>
    .main3{
        position: relative;
    }
    .child1{
        position: absolute;
        top: 50%;
        left: 50%;
        /* margin-left 负的自身宽度一半 */
        /* margin-top  负的自身高度一半 */
    }
</style>

最后总结:

一 : 给父级设置宽高100%,div设置绝对定位,left,right,top,bottom设置为0,margin:auto即可实现

二 : 利用绝对定位和tranform(过渡动画)实现,div绝对定位,left:50%;top:50%;然后设置transform:translate3d(-50%,-50%,0)即可

三 : flex弹性盒布局,给父级div设置dispaly:flex,设置水平和垂直居中justify-content:center align-items:center

四 : div设置绝对定位,left:50%;top:50%距离左和上是margin-left:cakc(-div自身宽度/2)
       margin-top:calc(-div自身高度/2),也可以自己计算margin-left和margin-top的值

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值