HTML代码
<div class="wrap"> <div class="box"></div> </div>
flex
.wrap { width: 300px; height: 300px; background-color: pink; display: flex; justify-content: center; align-items: center;}.box { height: 100px; width: 100px; background-color: plum;}
table-cell
.wrap {
width: 300px;
height: 300px;
background-color: pink;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
height: 100px;
width: 100px;
background-color: plum;
display: inline-block;
}
margin, transform
.wrap {
width: 300px;
height: 300px;
background-color: pink;
/* 解决外边距塌陷:加 border 或者overflow: hidden; */
border: 1px solid red;
}
.box {
height: 100px;
width: 100px;
background-color: plum;
margin: 50% auto;
transform: translateY(-50%);
}
inline-block, vertical-align
.wrap {
width: 300px;
height: 300px;
background-color: pink;
text-align: center;
line-height: 300px;
}
.box {
height: 100px;
width: 100px;
background-color: plum;
/* 重新设置子元素的行高,否则会继承父元素的行高 */
line-height: 100px;
display: inline-block;
/* middle 将元素放置在父元素的中部 */
vertical-align: middle;
}
absolute, 负margin
.wrap {
width: 300px;
height: 300px;
background-color: pink;
position: relative;
}
.box {
height: 100px;
width: 100px;
background-color: plum;
position: absolute;
left: 50%;
top: 50%;
/* 宽高的一半 */
margin-left: -50px;
margin-top: -50px;
}
absolute,margin:auto
.wrap {
width: 300px;
height: 300px;
background-color: pink;
position: relative;
}
.box {
height: 100px;
width: 100px;
background-color: plum;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
absolute,transform
.wrap {
width: 300px;
height: 300px;
background-color: pink;
position: relative;
}
.box {
height: 100px;
width: 100px;
background-color: plum;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
grid
.wrap {
width: 300px;
height: 300px;
background-color: pink;
display: grid;
}
.box {
height: 100px;
width: 100px;
background-color: plum;
align-self: center;
justify-self: center;
}