
image.png

image.png
居中元素寬高已知
1. absolute + margin auto
.parent {
position: relative;
width: 100px;
height: 100px;
border: 3px solid steelblue;
margin: 0 auto;
}
.child1 {
background: tomato;
width: 50px;
height: 50px;
/**關(guān)鍵代碼**/
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
2.absolute + 負margin
.parent {
position: relative;
width: 100px;
height: 100px;
border: 3px solid steelblue;
margin: 0 auto;
}
.child2 {
background: tomato;
width: 50px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px; /**寬度的一半**/
margin-left: -25px;
}
3.absolute + calc
.parent {
position: relative;
width: 100px;
height: 100px;
border: 3px solid steelblue;
margin: 0 auto;
}
.child3 {
background: tomato;
width: 50px;
height: 50px;
position: absolute;
top: calc(50% - 25px);
left: calc(50% - 25px);
}
居中元素寬高未知
4.absolute + transform
.parent {
position: relative;
width: 100px;
height: 100px;
border: 3px solid steelblue;
margin: 0 auto;
}
.child4 {
background: tomato;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
5.line-height + vertical-align
.parent5 {
width: 100px;
border: 3px solid steelblue;
margin: 0 auto;
/**關(guān)鍵代碼**/
line-height: 100px;
text-align: center;
}
.child5 {
background: tomato;
/**關(guān)鍵代碼**/
display: inline-block;
vertical-align: middle;
line-height: initial;
}
6.flex布局
.parent6 {
width: 100px;
height: 100px;
border: 3px solid steelblue;
margin: 0 auto;
/**關(guān)鍵代碼**/
display: flex;
justify-content: center;
align-items: center;
}
7.flex + margin auto
.parent7 {
width: 100px;
height: 100px;
border: 3px solid steelblue;
/**關(guān)鍵代碼**/
display: flex;
margin: 0 auto;
}
.child7 {
margin: auto;
}