宽高已知
.parent {
border: 1px solid #00ee00;
height: 300px;
position: relative;
}
.child {
width: 200px;
height: 200px;
border: 1px solid red;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px; // 自身宽度的一半
margin-top: -100px; // 自身高度的一半
}
宽高未知
.parent {
border: 1px solid #00ee00;
height: 300px;
position: relative;
}
.child {
border: 1px solid red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
文本居中
主要用于对文本、图片等水平居中时,给其父元素设置
div{
border:1px solid red;
margin:20px;
}
.txtCenter{
text-align: center;
height: 50px;
line-height: 50px;
}
定宽居中
.parent {
height: 400px;
border: 1px solid red;
}
.child {
border: 1px solid red;
width: 200px;
height: 200px;
margin: 0 auto;
margin-top: 100px; /* 父元素高度的一半减去子元素高度的一半 */
}
绝对定位 + margin
需要设置宽高
.parent {
height: 400px;
border: 1px solid red;
position: relative;
}
.child {
width: 200px;
height: 200px;
border: 1px solid sandybrown;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
Flex 布局
给父元素设置 flex
.parent {
border: 1px solid red;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
flex + auto
.parent {
border: 1px solid red;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
.child {
marign: auto;
}
table 布局
.parent {
height: 400px;
border: 1px solid red;
display: table-cell;
vertical-align: middle;
}
.child {
margin: 0 auto;
}
Grid 布局
grid + auto 同样也能实现居中
.parent {
border: 1px solid red;
height: 400px;
display: grid;
justify-items: center;
align-items: center;
}