需求:实现元素水平居中
思路:利用定位+margin:auto<子元素必须设置宽高>
利用定位+margin:负值<子元素必须设置宽高>
利用定位+transform<子元素宽高不要求>
table布局<子元素宽高不要求>
flex布局<子元素宽高不要求>
grid布局<子元素宽高不要求>兼容性相对比较差
1.利用定位+margin:auto
<style>
.father{
width:500px;
height:300px;
border:1px solid #f0f;
position: relative;
}
.child{
width:100px;
height:50px;
background: #f0f;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}
</style>
<div class="father">
<div class="child"></div>
</div>
&&这里使用子绝父相并且四个定位属性的值都设置了0,如果此时子级没有宽高,则会被拉伸和父级一样宽高
2.利用定位+margin:负值
<style>
.father {
position: relative;
width: 200px;
height: 200px;
background: #ff0;
}
.child{
position: absolute;
top: 50%;
left: 50%;
margin-left:-50px;
margin-top:-50px;
width: 100px;
height: 100px;
background: #f0f;
}
</style>
<div class="father">
<div class="child"></div>
</div>
3.利用定位+transform
<style>
.father {
position: relative;
width: 200px;
height: 200px;
background: ff0;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 100px;
height: 100px;
background: #f0f;
}
</style>
<div class="father">
<div class="child"></div>
</div>
4.table布局
<style>
.father {
display: table-cell;
width: 200px;
height: 200px;
background: #ff0;
vertical-align: middle;
text-align: center;
}
.child{
display: inline-block;
width: 100px;
height: 100px;
background: #f0f;
}
</style>
<div class="father">
<div class="child"></div>
</div>
&&设置父元素为display:table-cell,子元素设置 display: inline-block。利用vertical和text-align可以让所有的行内块级元素水平垂直居中
5.flex弹性布局
<style>
.father {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background: #ff0;
}
.child{
width: 100px;
height: 100px;
background: #f0f;
}
</style>
<div class="father">
<div class="child"></div>
</div>
6.grid网格布局
<style>
.father {
display: grid;
align-items:center;
justify-content: center;
width: 200px;
height: 200px;
background: #ff0;
}
.child{
width: 10px;
height: 10px;
border: 1px solid #f0f
}
</style>
<div class="father">
<div class="child"></div>
</div>