css
关于css设置元素水平垂直居中
页面代码:
<div class="par" style="width: 300px; height: 300px;">
<div class="sun" style="width: 100px; height: 100px; "></div>
</div>
css代码:
第一种:
.par {
display: flex;
justify-content: center;
align-items: center;
}
第二种:
.par {
position: relative;
}
.par .sun {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
第三种:
.par {
position: relative;
}
.par .sun {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
第四种:
.par {
}
.par .sun{
position: relative;
top: 50%;
transform: translateY(-50%);
margin-left: auto;
margin-right: auto;
}
第五种:
.par {
position: relative;
}
.par .sun{
position: absolute;
left: 50%;
margin-left: -50px;
top: 50%;
margin-top: -50px;
}
效果图如下:

浙公网安备 33010602011771号