实现盒子居中

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

  只对块级元素起作用

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>            

猜你喜欢

转载自www.cnblogs.com/belongs-to-qinghua/p/11212290.html