1. 程式人生 > >div+css盒子居中

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>