1、已知子元素的高度和宽度,父元素相对定位,子元素绝对对定位。
<div class="parent">
<div class="child">子元素</div>
</div>
.parent {
border: 1px solid #888;
width: 300px;
height: 300px;
padding: 20px;
position: relative;
}
.child {
background-color: #f40;
width: 150px;
height: 150px;
position: absolute;
left: calc(50% - 75px);
top: calc(50% - 75px);
}
2、子元素的高度和宽度不知,父元素相对定位,子元素绝对定位,然后利用CSS3的transform属性。
.parent {
border: 1px solid #888;
width: 300px;
height: 300px;
padding: 20px;
position: relative;
}
.child {
background-color: #f40;
position: absolute;
transform: translateX(-50%) translateY(-50%);
left: 50%;
top: 50%;
}
3、子元素的高度和宽度不知,利用flex布局。
.parent {
border: 1px solid #888;
width: 300px;
height: 300px;
padding: 20px;
display: flex;
align-items: center;
justify-content: center;
}
.child {
background-color: #f40;
}