元素居中

HTML:

<div class="div1"></div>
<div class="div2"></div>
<div class="div3"><img src="img/apple.jpg"></div>
<div class="inner-table">
        <div class="div4"><img src="img/apple.jpg"></div>
</div>
<div class="div5"></div>
<div class="div6">居中。。。。<img src="img/apple.jpg"></div>
<div class="div7">sdfsfsdf</div>
<div class="div8"><div class="centered">居中</div></div>

CSS:

    /*第一种方法*/
    /*兼容所有浏览器,但是宽高必须有固定值,灵活度低*/

.div1{
    position:absolute;
    width:100px;
    height:100px;
    background-color: red;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
}


/*第二种*/
/*避免重复计算margin负数值,宽高可以任意变化值,元素都是在中心,此方法适合移动端。ie6 + ie7 不支持*/
.div2{
    position:absolute;
    width:100px;
    height:100px;
    margin: auto;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background-color: yellow;
}

/*第三种*/
.div3{
    display: table-cell;
    width: 198px;
    height: 198px;
    text-align: center;
    vertical-align: middle;
    float: -left;
    background-color: red
    float:-left;   /*添加浮动后垂直居中会失效*/
}
.div3 img{
    width: 50%;
}

/*第四种*/
/*在div外面套一个div,并给外面的div设置为table属性,内表单模型*/
.inner-table{
    display: table;
    width: 100%;
    height: 100%;
}
.div4{
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    background-color: red
}
.div4 img{
    width: 50%;
    display: block;
    margin: 0 auto;
}

/* 第五种 */
.div5{
    position: fixed;
    margin:  auto;
    top:0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 150px;
    height: 150px;
    background-color: blue;
}

/*第六种*/
/* ie9以下不支持  */
.div6{
    height: 200px;
    display: -webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;
}
.div6 img{
    width: 20%;
    display:block;
}


/* 第七种 */
.div7{
    width: 80px;
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform:translate(-50%, -50%);
   transform:translate(-50%, -50%);
    background-color: orange;
}

/*第8种*/
.div8{
    position: relative;
    text-align: center;
    height: 198px;
}
.div8:before{
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    background: #000;
}
.centered{
    display: inline-block;
    vertical-align: middle;
    width: 198px;
    background-color: green;
}

 

posted @ 2016-12-22 18:24  Koidt  阅读(253)  评论(0编辑  收藏  举报