垂直居中的几种方式

页面中垂直居中的几种方法:

1. 通过使用absolute定位来实现垂直居中
在需要垂直居中的元素的长宽已知的情况下可以使用此方法。
HTML:
    <div class="bg">
        <div class="center-div">
            <img src=""/>
        </div>
    </div>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
CSS:
    <style type="text/css">
        .bg{
            position: relative;
            background: #dfdfdf;
            width: 400px;
            height: 400px;
        }
        .center-div{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left:-50px;
            margin-top:-50px; 

        }
    </style>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
需要垂直居中的元素的长宽设定为已知的 100px。
在父级元素设定position:relative属性,在需要垂直居中的元素设置position:absolute属性,设置top:50% ,left:50%;根据父级元素来做垂直元素的右上角定位,其位置与父级元素中心点重合,然后用margin属性带负值来移动使居中元素的中心点与父级中心点重合,实现居中。

![这里写图片描述](https://img-blog.csdn.net/20160419110811404) 
2. 使用table实现居中
    <table style="width: 400px;height:400px;background:#dfdfdf;">
        <tr>
            <td>
                <img src="" style="width: 100px;height:100px;background:red;">
            </td>
        </tr>
    </table>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

td单元格内内容会默认继承vertical-align垂直居中显示. 
这里写图片描述

当然,如果觉得用table觉得语义化不好,也可以用div来实现相同效果,只需要添加 display:table 属性:

    <div style="display: table; width: 400px;height:400px;background:#dfdfdf;">
        <div style="display: table-cell;vertical-align: middle;">
            <img src="" style="width: 100px;height:100px;background:red;">
        </div>
    </div>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
3. 使用display:flex实现居中
    <div style="display:flex; width: 400px;height:400px;background:#dfdfdf;">
        <div style="margin: auto;">
            <img src="" style="width: 100px;height:100px;background:red;">
        </div>
    </div>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5

给父级添加display:flex属性,然后给居中元素添加margin:auto,就可以实现水平和垂直居中。不过可能部分浏览器不支持。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值