css居中總結

看風景就發表於2015-07-28

水平居中

1. inline和inline-*元素水平居中:text-align:center

2. block元素水平居中

block定寬:margin-left: auto; margin-right; auto;

block不定寬:

a. 轉為inline-block元素,使用text-align: center
b. 使用display:table模擬table,同時設定左右margin:auto即可
c. table標籤包裹,設定table的左右margin:auto即可

3. fit-content和margin auto居中(可實現容器寬度隨內容增多而自動增大)

.box{
  width: -moz-fit-content;
  width: -webkit-fit-content;
  width:fit-content;
  margin:0 auto;
}

4. 左右拉伸和margin auto居中(定寬度的absolute元素水平居中)

.box{
  position:absolute;
  left:0;
  right:0;
  margin:0 auto;
   width: 300px;  
}

垂直居中

1. 父元素高度不定

(inline,inlie-*,block)垂直居中: 父元素上下內邊距相等 padding-top = padding-bottom

2. 父元素高度確定

inline和inline-*豎直居中

單行文字豎直居中: line-height與父元素高度相同

多行文字等其他豎直居中: (模擬td)display:table-cell;vertical-align:middle;

block豎直居中:

a. block定高: position: absolute; top: 50%; margin-top: -height/2
b. block不定高:

<1. (模擬td)display:table-cell;vertical-align:middle;
<2. (模擬table) 父容器display:table, 子容器display:table-cell

.parent {display: table;}

.child {
    display: table-cell;
    vertical-align: middle;
}

<3. transform方法:position: releative或者absolute; top: 50%; transform: translateY(-50%)

3. 上下拉伸和margin auto居中(定高度的absolute元素垂直居中)

.box{
  position:absolute;
  top:0;
  bottom:0;
  margin:auto 0;
   height: 300px;
}

4. 偽元素撐開對齊

.parent{
  font-size:0;//消除inline-block水平空隙
}
.son,.parent:after{
  display:inline-block;
  vertical-align:middle;
  font-size:24px;//修正字型
}
.parent:after{
  content:'';
  height:100%;
}

5. writing-mode配合text-align或margin:0 auto實現垂直居中

 

.verticle-mode {
    writing-mode: tb-lr;
    writing-mode: vertical-lr;
    -webkit-writing-mode: vertical-rl;
}
.horizontal-mode{
    writing-mode: lr-tb;
    writing-mode: horizontal-tb;
    -webkit-writing-mode: horizontal-rl;
}

 

<div class="item">
     <span class="item-left">1. </span>
     <span class="item-right">標題</span>
</div>
.item{
     height:60px;background-color:lightcoral;border-radius: 8px;padding:5px 10px;line-height: 30px;
     writing-mode: tb-lr;
     -webkit-writing-mode: vertical-lr;      
     writing-mode: vertical-lr;
     text-align: center;
}
.item *{
     writing-mode: lr-tb;
     writing-mode: horizontal-tb;     
}

水平垂直居中

1. absolute元素水平居中(缺點:元素中內容很長,會導致超出內容不可見)

.center_middle{
  position:absolute;
  left:0;
  top:0;
  right:0;
  bottom:0;
  margin:auto;
   width: 800px;
   height: 600px;
}

 

2. flex

flex正統

.parent {
    display: flex;
    align-items: center;
    justify-content: center;
}

flex + margin:auto

.parent {
    display: flex;
    margin: 0;
    >.child {
        margin: auto;
    }
}