CSS/CSS3 實現 居中(水平&垂直)

1,水平居中:行內元素css

把行內元素放在一個屬性塊(display:block)元素中,而後設置父層元素屬性居中:css3

.test {佈局

text-align:center;

}flex

2,水平居中:塊狀元素flexbox

設置外邊距code

.test {orm

margin: 100px auto;

}it

3,水平居中:多個塊狀元素io

把塊狀元素屬性(display:inline-block),而後設置父層元素屬性居中:table

.test {

text-align:center;

}

4,水平居中:多個塊狀元素(flexbox佈局實現)

把塊狀元素的父元素屬性 display:flex和justify-content:center,以下設置:

.test {

text-align:center;

}

5,垂直居中:單行的行內元素

設置height和line-height屬性

.test {

height: 100px;
line-height:100px;

}

6,垂直居中:多行的行內元素

給要居中的父元素設置display:table-cell和vertical-align:middle屬性

.test {

background: red;
width: 200px;
height: 200px;
/* 如下屬性垂直居中 */
display: table-cell;
vertical-align:middle;

}

7,垂直居中:已知高度的塊狀元素

給要居中的元素設置以下屬性

.test {

top: 50%;
margin-top: -50px;  /* margin-top值爲自身高度的一半 */
position: absolute;
padding:0;

}

8,水平垂直居中:已知高度和寬度的元素

給要居中的元素設置以下屬性

(1)
.test {

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

}
(2)
.test{

position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;  /* 設置margin-left / margin-top 爲自身高度的一半 */
margin-left: -75px;

}

9,水平垂直居中:未知高度和寬度元素

給要居中的元素設置以下屬性

.test {

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);  /* 使用css3的transform來實現 */

}

10,水平垂直居中:可用flex

設置以下屬性

.test {

display: flex;
justify-content:center;
align-items: center;
/* 注意這裏須要設置高度來查看垂直居中效果 */
background: #AAA;
height: 300px;

}

相關文章
相關標籤/搜索