- 方法一
父元素设置为flex布局,并设置justify-content:center和align-items:center,令其主轴和交叉轴的对齐方式为居中
<div class="fu">
<div class="son">
子元素
</div>
</div>
.fu {
height: 500px;
width: 500px;
background-color: burlywood;
display: flex;
justify-content: center;
align-items: center;
}
.son {
height: 100px;
width: 100px;
background-color: red;
}
- 方法二
父元素设置为flex布局,子元素的margin设置为auto
<div class="fu">
<div class="son">
子元素
</div>
</div>
.fu {
height: 500px;
width: 500px;
background-color: burlywood;
display: flex;
}
.son {
height: 100px;
width: 100px;
background-color: red;
margin:auto;
}
- 方法三
父元素设置为绝对定位,position:relative,子元素设置为绝对定位,position: absolute;设置距离top:50%,左边left:50%,设置transform:translate(-50%,-50%)
<div class="fu">
<div class="son">
子元素
</div>
</div>
.fu {
height: 500px;
width: 500px;
background-color: burlywood;
position: relative;
}
.son {
height: 100px;
width: 100px;
background-color: red;
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
}