垂直水平居中的方法
块级元素
1.Flex
关键语句:display: flex;(弹性盒子)
justify-content: center;(左右居中)
align-items: center;(垂直居中)
.songtao{
width: 500px;
height: 300px;
background-color: dodgerblue;
margin: auto;
/* 添加样式 */
display: flex;
justify-content: center;
align-items: center;
}
2.display + margin
关键语句:父元素display: flex;(弹性盒子)
子元素margin: auto;(上下左右居中)
.songtao{
width: 500px;
height: 300px;
background-color: dodgerblue;
margin: auto;
/* 添加样式 */
display: flex;
}
.center{
width: 100px;
height: 100px;
background-color: red;
/* 添加样式 */
margin: auto;
}
注意:此方法只能完美居中一个子元素,如果子元素不止一个,则所有子元素垂直居中、左右均匀占据父容器所有空间
3.table-cell
关键语句:父元素display: table-cell;
vertical-align: middle;
子元素margin: auto;
(或)table-cell + display
关键语句:父元素display: table-cell;
vertical-align: middle;
text-align: center;
子元素display: inline-block;
.songtao{
width: 500px;
height: 300px;
background-color: dodgerblue;
margin: auto; /* 失效 */
/* 添加样式 */
display: table-cell;
vertical-align: middle;
}
.center{
width: 100px;
height: 100px;
background-color: red;
/* 添加样式 */
margin: auto;
}
4.position + translate
关键语句:父元素position: relative;
子元素position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
.songtao {
width: 500px;
height: 300px;
background-color: dodgerblue;
margin: auto;
/* 添加样式 */
position: relative;
}
.center {
width: 100px;
height: 100px;
background-color: red;
/* 添加样式 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
5.position + margin
关键语句:父元素position: relative;
子元素position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
.songtao {
width: 500px;
height: 300px;
background-color: dodgerblue;
margin: auto;
/* 添加样式 */
position: relative;
}
.center {
width: 100px;
height: 100px;
background-color: red;
/* 添加样式 */
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
6.position+calc( )
关键语句:父元素position: relative;
子元素position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
.songtao {
width: 500px;
height: 300px;
background-color: dodgerblue;
margin: auto;
/* 添加样式 */
position: relative;
}
.center {
width: 100px;
height: 100px;
background-color: red;
/* 添加样式 */
position: absolute;
/* 不一定为50px,根据被居中元素宽、高确定,支持百分数%*/
top: calc(50% - 50px);
left: calc(50% - 50px);
}
行级元素
1.line-height + text-align
关键语句:父元素 text-align: center;
子元素line-height:父元素height;
.songtao {
width: 500px;
height: 300px;
background-color: dodgerblue;
margin: auto;
/* 添加样式 */
text-align: center;
}
.center {
width: 100px;
height: 100px;
background-color: red;
/* 添加样式 */
line-height: 300px;
}
2.display + vertical-align
关键语句:父元素 display: table;
子元素display: table-cell;
vertical-align: middle;
text-align: center;
.songtao {
width: 500px;
height: 300px;
background-color: dodgerblue;/* 失效 */
margin: auto;
/* 添加样式 */
display: table;
}
.center {
width: 100px;
height: 100px;
background-color: red;
/* 添加样式 */
display: table-cell;
vertical-align: middle;
text-align: center;
}