div+css盒子居中

7 篇文章 0 订阅

1.利用margin

优点:兼容性好
缺点:必须知道内容盒子的高度才可以,有了这点限制;

div1的宽减去div2的宽就是div2margin-left的数值:(100-40)/2=30
div1的高减去div2的高就是div2margin-top的数值:(100-40)/2=30

 <style type="text/css">
            .div1{  width: 100px; height: 100px; border: 1px solid #000000;} 
            .div2{ width:40px ; height: 40px; background-color: green;}
            .div22{
                margin-left: 30px;margin-top: 30px;
            }
        </style>
        <div class="div1">
            <div class="div2 div22">
            </div>
        </div>

2. position+50%

缺点:IE6及以上

把div2相对于div1的top、left都设置为50%,然后再用margin-top设置为div2的高度的负一半拉回来,用margin-left设置为宽度的负一半拉回来

<style type="text/css">
            .div1{  width: 100px; height: 100px; border: 1px solid #000000;} 
            .div2{ width:40px ; height: 40px; background-color: green;}
 
            .div11{
                position: relative;
            }
            .div22{
                position: absolute;top:50%;left: 50%;margin-top: -20px;margin-left: -20px;
            }
        </style>
 
        <div class="div1 div11">
            <div class="div2 div22">
 
            </div>
        </div>

3.position+margin:auto

缺点:不兼容ie6,7

<style type="text/css">
            .div1{  width: 100px; height: 100px; border: 1px solid #000000;} 
            .div2{ width:40px ; height: 40px; background-color: green;}
 
            .div11{
                position: relative;
            }
            .div22{
                position: absolute;margin:auto; top: 0;left: 0;right: 0;bottom: 0;
            }
        </style>
 
        <div class="div1 div11">
            <div class="div2 div22">
 
            </div>
        </div>

4.table-cell+vertical-align:middle+margin:auto

<style>
    .div1{
        width: 100px;
        height:100px;
        border: 1px solid #000;
        display: table-cell;
        vertical-align: middle;
    }
    .div2{width:50px;height:50px;background: yellow;margin: auto}
</style>
<div class="div1">
    <div class="div2"></div>
</div>

5.flex

缺点:不支持IE

<style>
    .div1{
        width: 100px;
        height:100px;
        border: 1px solid #000;
        display: flex;
        align-items: center;
        jusstify-content: center;
    }
    .div2{width:50px;height:50px;background: yellow;}
</style>
<div class="div1">
    <div class="div2"></div>
</div>

6.position+transform

<style>
    .div1{
        width: 100px;
        height:100px;
        border: 1px solid #000;
        position: relative;
    }
    .div2{width: 80px;height: 80px;background: yellow;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);}
</style>
<div class="div1">
    <div class="div2"></div>
</div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值