垂直(上下)居中的方式:
前提條件:
<div id="parent">
<div id="child">child</div>
</div> ```
parent{
width:200px;
height:200px;
border: 1px solid black;
}
child{
width:100px;
height:100px;
border: 1px solid black;
}
1.
parent {
position:relative;
}
child {
position:absolute;
top:50%;
margin:-50px 0 0 0; /* 這個(gè)值要取div高度的一半*/
}
2.
parent{
position: flex;
}
child {
margin: auto;
/*或者*/
align-items: center;
}```
/*這里子元素將會(huì)盡可能的填充父元素,內(nèi)部文字會(huì)居中*/
#parent {
display: table;
}
#child {
display: table-cell;
vertical-align:middle;
}```
4.
parent {
position: relative;
}
child {
position: absolute;
bottom: 0;
top: 0;
margin: auto;
}
水平居中:
/子元素 div/
#child {
margin: 0 auto;
}
/父元素 讓父元素中的文字水平居中/
#parent {
text-align:center;
}```
比較:
- text-align: 是設(shè)置文本的對(duì)齊方式,寫在包裹文本的標(biāo)簽上
- vertical-align: 設(shè)置圖片的對(duì)齊方式,沒有 center 屬性值。
內(nèi)聯(lián)元素居中
水平居中:
- 行內(nèi)元素:text-align:center
- flex 布局:display:flex;justify-content:center
垂直居中設(shè)置:
- 父元素高度確定的單行文本(內(nèi)聯(lián)元素):height:line-height
- 父元素高度確定的多行文本(內(nèi)聯(lián)元素)
- 插入 table,然后設(shè)置 vertical-align:middle
- 設(shè)置:display:table-cell;vertical-align:middle
塊級(jí)元素居中
水平居中:
- 定寬塊狀:margin:auto
- 不定寬:
- 在元素外加入 table 標(biāo)簽(完整的 table,tbody,tr,td),該元素寫在 td 內(nèi),然后設(shè)置 margin 的值為 auto
- 給該元素設(shè)置 display:inline
- 父元素設(shè)置:position:relative;left:50%
子元素設(shè)置:position:relative;left:50%
垂直居中
/*使用position:absolute(fixed),設(shè)置left、top、margin-left、margin-top的屬性;*/
.box{
position:absolute;/*或fixed*/
top:50%;
left:50%;
margin-top:-100px;
margin-left:-200px;
}
/*利用position:fixed(absolute)屬性,margin:auto這個(gè)必須不要忘記了;*/
.box{
position: absolute;或fixed
top:0;
right:0;
bottom:0;
left:0;
margin: auto;
}
/*利用display:table-cell屬性使內(nèi)容垂直居中;*/
.box{
display:table-cell;
vertical-align:middle;
text-align:center;
width:120px;
height:120px;
background:purple;
}
/*使用css3的新屬性transform:translate(x,y)屬性;*/
.box{
position: absolute;
transform: translate(50%,50%);
-webkit-transform:translate(50%,50%);
-moz-transform:translate(50%,50%);
-ms-transform:translate(50%,50%);
}
/*最高大上的一種,使用:before元素;*/
.box{
position:fixed;
display:block;
background:rgba(0,0,0,.5);
}
.box:before{
content:'';
display:inline-block;
vertical-align:middle;
height:100%;
}
.box.content{
width:60px;
height:60px;
line-height:60px;
color:red;
}
flex 布局:
略