水平居中
1、子元素为行内元素:父text-align: center;
.parent {
background-color: violet;
text-align: center;
}
.child {
background-color: yellow;
}
2、子元素为块级元素定宽:子margin: 0 auto
.parent {
background-color: violet;
}
.child {
width: 100px;
background-color: yellow;
margin: 0 auto;
}
3、子元素为块级元素:子position:absolute + trabsform
.child {
background-color: yellow;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
4、子元素为块级元素定宽:子absolute + width + margin-left
.child {
width: 100px;
background-color: yellow;
position: absolute;
left: 50%;
margin-left: -50px;
}
垂直居中
1、子元素为单行文本
.parent {
background-color: violet;
line-height: 100px;
}
.child {
background-color: yellow;
}
2、display:table + vertical-align: middle
vertical-align: middle只在父层是td或th才生效
.parent {
background-color: violet;
height: 100px;
display: table;
}
.child {
background-color: yellow;
display: table-cell;
vertical-align: middle;
}
水平垂直居中
1、flex
.parent {
background-color: violet;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
}
.child {
background-color: yellow;
}
2、子不定高
.parent {
background-color: violet;
height: 100px;
position: relative;
}
.child {
background-color: yellow;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
3、子定高
.parent {
background-color: violet;
height: 100px;
position: relative;
}
.child {
background-color: yellow;
position: absolute;
left: 50%;
top: 50%;
width: 100px;
height: 60px;
margin-left: -100px;
margin-top: -30px;
}
4、position: absolute; + margin: auto;
.parent {
background-color: violet;
}
.child {
background-color: yellow;
width: 200px;
height: 200px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
5、table-cell
.parent {
background-color: violet;
height: 100px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child {
background-color: yellow;
}