div水平居中及div水平垂直居中的方法總結

水平居中

1、margin:auto

<div class="wrap">
   <div class="wrap-txt"></div>
</div>

.wrap{
   width: 100%;
}
.wrap-txt{
    width: 6rem;
    height: 2rem;
    background: #00FFFF;
    margin: auto;
}

2、text-align:center
3、absolute+margin偏移

<div class="wrap">
   <div class="wrap-txt"></div>
</div>

.wrap{
   width: 100%;
}
.wrap-txt{
    width: 6rem;
    height: 2rem;
    background: #00FFFF;
    position: absolute;
    left: 50%;
    margin-left: -3rem;
}

4、display:box

<div class="box-pack">文字</div>
.box-pack{
    width: 60px;
    height: 30px;
    display: -webkit-box;
    -webkit-box-pack: center;
    background: #0894ec;
}

5、absolute+transform

垂直居中

1、line-height

<div class="wrap-txt">文字</div>
.wrap-txt{
    width: 6rem;
    height: 2rem;
    line-height: 2rem;
    border: 1px solid transparent;
    box-sizing: border-box;
    background: #00FFFF;
}

2、absolute+margin偏移

<div class="wrap">
   <div class="wrap-txt"></div>
</div>

.wrap{
   width: 100%;
}
.wrap-txt{
    width: 6rem;
    height: 2rem;
    background: #00FFFF;
    position: absolute;
    top: 50%;
    margin-top: -3rem;
}

3、absolute+transform

<div class="parent">
    <div class="child">文字</div>
</div>

.parent{
    position: relative;
    width: 5rem;
    height: 3rem;
    background: #ccc;
}
.child{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

4、table-cell

<div class="table-cell">
    <div class="table-cell-txt">文字</div>
</div>

.table-cell{
    width: 60px;
    height: 30px;
    display: table-cell;
    vertical-align: middle;
    background: #ccc;
}

5、絕對定位+四個方向爲零+margin:auto(必須設置子元素的寬高,否則子元素的寬高等於父元素的寬高)

<div class="absolute-zero">
    <div class="absolute-zero-txt">文字</div>
</div>

.absolute-zero{
    width: 60px;
    height: 30px;
    background: #f54656;
    position: relative;
}
.absolute-zero-txt{
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 50px;
    height: 20px;
    background: #00FFFF;
    margin: auto;
}

6、css3的flex(存在兼容問題)
7、display:box

<div class="box-align">文字</div>
.box-pack{
    width: 60px;
    height: 30px;
    display: -webkit-box;
    -webkit-box-align: center;
    background: #0894ec;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章