水平居中
文本水平居中
{
text-align: center
}
内边距水平居中
需要父元素和子元素都有宽度,且子元素为块状元素
{
display: block
margin: 0 auto
}
设置内联块状通过text-align水平居中
.parent{
text-align: center
}
.children{
display:inline-block
}
flex布局水平居中
在父元素使用display:flex
.parent{
display:flex
justify-content: center
}
grid布局水平居中
.container {
display: grid;
justify-items: center;
}
table布局水平居中
.parent{
display:table
}
.children{
display:table-cell
text-align: center
}
定位布局和transform水平居中
适用于已知或未知元素自身宽高情况
.parent{
position: relative
}
.children{
position: absolute
left: 50%
top: 10%
transform: translate(-50%, -50%);
}
定位布局和外边距水平居中
适用于已知元素自身宽高情况
.parent{
position: relative;
}
.children{
position: absolute;
width: 100px;
left: 50%
top: 10%
margin-top: -100px;
margin-left: -50px;
}
垂直居中
行内元素垂直居中
父元素设置height和lineheight等高
{
height: 100px;
line-height: 100px;
}
flex布局垂直居中
.parent{
display:flex
align-items: center
}
grid布局垂直居中
.parent{
display:grid
align-items: center
}
table布局垂直
.parent{
display:table
}
.children{
display:table-cell
vertical-align: middle
}
定位布局和transform垂直居中
适用于已知或未知元素自身宽高情况
.parent{
position: relative
}
.children{
position: absolute
left: 10%
top: 50%
transform: translate(-50%, -50%);
}
定位布局和外边距垂直居中
适用于已知元素自身宽高情况
.parent{
position: relative;
}
.children{
position: absolute;
height: 100px;
left: 10%
top: 50%
margin-top: -50px;
margin-left: -10px;
}
居中布局比较简单 推荐使用flex和grid布局,position和table根据实际需要选择使用。