實現盒子居中


一、標准流下的盒子水平居中

  只對塊級元素起作用

margin: 0 auto;

 

二、絕對定位的盒子水平、豎直居中

1.通過具體的計算,讓盒子居中

position: absolute;
/* 移動父元素寬度的一半 */
left: 50%;
top: 50%;
/* 移動的是元素本身自己的一半 */
margin-left: -60px;
margin-top: -25px;

2.不用具體計算的居中

position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;

3.2D位移方式實現定位元素居中

position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); //這里是參照元素自身

 

三、伸縮盒子實現居中

  對父元素進行設置

display: flex;
align-items: center;
justify-content: center;

 

四、利用css3的新增屬性table-cell, vertical-align:middle;

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

    .div11{
        display: table-cell;vertical-align: middle;
    }
    .div22{
        margin: auto;
    }
</style>

<div class="div1 div11">
    <div class="div2 div22">
    </div>
</div>            


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM