居中的几种方式
<div class="father">
<div class="son"></div>
</div>
<style>
/* 第一种利用定位 各个方向为0和margin auto*/
.father{
width: 300px;
height: 300px;
border: 1px solid #222;
position: relative;
}
.son{
width: 100px;
height: 100px;
background:#379;
position: absolute;
top: 0;
bottom:0;
left: 0;
right: 0;
margin: auto;
}
/* 第二种定位 50% 和-margin */
.father{
width: 300px;
height: 300px;
border: 1px solid #222;
position: relative;
}
.son{
width: 100px;
height: 100px;
background:#379;
position: absolute;
left:50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}*/
/* 第三种定位利用calc */
.father{
width: 300px;
height: 300px;
border: 1px solid #222;
position: relative;
}
.son{
width: 100px;
height: 100px;
background:#379;
position: absolute;
left:calc(50%-50px);
top:calc(50%-50px);
}*/
/* 第四种利用transform */
.father{
width: 300px;
height: 300px;
border: 1px solid #222;
position: relative;
}
.son{
width: 100px;
height: 100px;
background:#379;
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%)
}
/* 第五种flex */
.father{
width: 300px;
height: 300px;
border: 1px solid #222;
display: flex;
justify-content: center;
align-items: center;
}
.son{
width: 100px;
height: 100px;
background:#379;
}
/* 第六种table-cell 子元素inline-block*/
.father{
width: 300px;
height: 300px;
border: 1px solid #222;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.son{
width: 100px;
height: 100px;
background:#379;
display: inline-block;
}
/* 第七种用grid */
.father {
width: 300px;
height: 300px;
border: 1px solid #222;
display: grid;
}
.son {
width: 100px;
height: 100px;
background: #379;
align-self: center;
justify-self: center;
}
</style>
网友评论