实现div居中的几种方法

方法一、使用display:table-cell

样式

<style>
.wrapperbox{border:1px solid red; width:100px; height:100px; display:table-cell; font-size:0; text-align:center; vertical-align:middle; *position:relative;padding:0; overflow:hidden; } 
.innerbox{text-align:center; vertical-align:middle; width:100px\9; *width:auto;font-size:0; *position:absolute;*top:50%;*left:50%;}
 img{ max-height:100px; max-width:100px; *position:relative;*bottom:50%;*right:50%;margin:0 auto;}
</style>

html

<div class="wrapperbox"> 
  <div class="innerbox"> 
     <img src="demo.png" />
  </div>
</div>

此方法div包括层过多;
兼容性:除IE 10及以下不兼容外,谷歌、360、火狐亲测兼容

方法二、使用绝对定位实现居中

样式

<style type="text/css">  
.content {  
    background: #dedede;  
    width:500px;
    height:500px;
    position:relative;
    }  
.content div{
    background: red;
    width:300px;
    height:300px;
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%); 
}
</style> 

html

    <div class="content">
      <div>test</div>
    </div> 

兼容性:IE 8以上兼容、谷歌、360、火狐亲测兼容

方法三、使用绝对定位实现全屏居中

样式

    <style>
        body{
            margin:0px;
            width:100%;
            height:100%;
        }
        .box{
            position:absolute;
            top:50%;
            left:50%;
            width:500px;
            height:200px;
        }
        .content{
            position:relative;
            top:-50%;
            left:-50%;
            width:100%;
            height:100%;
            background:red;
        }
    </style>

html

    <div class="box">
        <div class="content">
        </div>
    </div>

兼容性:全部兼容

方法四、使用display:flex

样式

    <style>
    /*居中div的父级*/
.parent{display:flex;justify-content:center;align-items:center;}
    </style>

兼容性:IE10及IE10以上、谷歌、360、火狐亲测兼容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值