div+css盒子居中

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>

猜你喜欢

转载自blog.csdn.net/qq_34035425/article/details/85013044