CSS居中
所有例子共用以下代码
<!--html-->
<div id="outer">
<div class="inner">
</div>
</div>
绝对定位
-
50%的父元素宽高减去自身宽高的50%
/*css*/ #outer { width: 500px; height: 300px; border: 5px solid deeppink; margin: 100px auto; position: relative;/*遵循父相子绝原则(父元素相对定位,子元素绝对定位)*/ } .inner { width: 200px; height: 100px; border: 5px solid burlywood; position: absolute;/*采用绝对定位脱离文档流,不然left与top无效*/ left: 50%;/*父元素的width的50%*/ top: 50%;/*父元素的height的50%*/ transform: translateX(-50%) translateY(-50%);/*平移元素自身宽高的50%*/ }
-
利用绝对定位的特性,给定left、right、top、bottom相同值,利用margin自适应
.inner { width: 200px; height: 100px; border: 5px solid burlywood; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; }
flex布局
这是在父元素上添加样式
/*css*/
#outer {
width: 500px;
height: 300px;
border: 5px solid deeppink;
margin: 100px auto;
display: flex;
align-items: center;/*垂直居中*/
justify-content: center;/*水平居中*/
}
.inner {
width: 200px;
height: 100px;
border: 5px solid burlywood;
}
grid布局
#outer {
width: 500px;
height: 300px;
border: 5px solid deeppink;
margin: 100px auto;
display: grid;
align-items: center;/*垂直居中*/
justify-items: center;/*水平居中*/
/* 可直接写成一句 */
/* place-items: center center; */
}
.inner {
width: 200px;
height: 100px;
border: 5px solid burlywood;
}
grid布局又叫网格布局,可将一行分为多列,一列分为多行
#outer {
width: 500px;
height: 300px;
border: 5px solid deeppink;
margin: 100px auto;
display: grid;
grid-template-columns: 100px 300px 100px;/*一行分为多少份,每份多宽*/
grid-template-rows: 100px 100px 100px;/*一列分为多少行,每行多高*/
}
.inner {
width: 200px;
height: 100px;
border: 5px solid burlywood;
place-self: center center;/*自身居中*/
/*
相当于以下样式的简写
align-self: center;
justify-self: center;
*/
grid-column-start: 2;/*垂直起始网格线*/
grid-row-start: 2;/*水平起始网格线*/
}
从下图显然可见,表格线
table-cell布局
利用表格特性
#outer {
width: 500px;
height: 300px;
border: 5px solid deeppink;
margin: 100px auto;
display: table-cell;
vertical-align: middle;/*垂直居中*/
text-align: center;/*水平居中*/
}
.inner {
width: 200px;
height: 100px;
border: 5px solid burlywood;
display: inline-block;/*子元素必须为行内元素或行内块元素*/
}
水平居中
- 利用margin
#outer { width: 500px; height: 300px; border: 5px solid deeppink; margin: 100px auto; } .inner { width: 200px; height: 100px; border: 5px solid burlywood; margin: 0 auto; }
- 利用text-align,子元素必须为行内元素或行内块元素
#outer { width: 500px; height: 300px; border: 5px solid deeppink; margin: 100px auto; text-align: center; } .inner { width: 200px; height: 100px; border: 5px solid burlywood; display: inline-block; }