一、快速居中对齐方法:给父级添加弹性布局(display: flex;),之后给自己添加(margin:auto;)
<style>
.content {
width: 500px;
height: 500px;
background: rgb(159, 220, 255);
display: flex;
}
.box {
margin: auto;
background-color: #fff;
}
</style>
<div class="content">
<div class="box">
<span>
快速居中对齐
</span>
</div>
</div>
二、不知宽高情况下居中
1.给父元素添加CSS:弹性布局(display: flex;)、水平对齐(justify-content: center;)、垂直对齐(align-items: center;)
<div class="content">
<div class="box">
<span>
父元素{<br>
display: flex;<br>
justify-content: center;<br>
align-items: center;<br>
}<br>
</span>
</div>
</div>
<style>
.content {
background-color: aqua;
width: 500px;
height: 500px;
display: flex;
justify-content: center;
align-items: center;
}
.box {
background-color: cadetblue;
}
</style>
2. 利用display:table-cell; 但是会使一些css无效,如margin
<style>
.content {
background-color: aqua;
width: 500px;
height: 500px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box {
background-color: cadetblue;
}
</style>
<div class="content">
<div class="box">
<span>
父元素{<br>
display:table-cell;<br>
vertical-align: middle;<br>
text-align: center;<br>
}<br>
子元素{<br>
display: inline-block;<br>
}<br>
</span>
</div>
</div>
3.利用绝对定位 position: absolute;,以父级的左上角为轴,设top和left为50%,之后在以自己为轴 transform: translate(-50%, -50%);
<style>
.content {
background-color: aqua;
width: 500px;
height: 500px;
position: absolute;
}
.box {
background-color: cadetblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<div class="content">
<div class="box">
<span>
父元素{<br>
position: absolute; <br>
}<br>
子元素{<br>
position: absolute; <br>
top: 50%; <br>
left: 50%; <br>
transform: translate(-50%, -50%); <br>
}<br>
</span>
</div>
</div>