1 flex布局法
html
<div class="box">
<div></div>
</div>
scss
.box {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
div {
width: 100px;
height: 100px;
background-color: #c1cbd7;
}
}
结果展示
Screen Shot 2020-06-02 at 10.45.50 AM.png
Screen Shot 2020-06-02 at 10.46.05 AM.png
2 position:absolute +负数 margin 或者transform
<div class="container">
<div class="box">
<div></div>
</div>
</div>
.box {
position: relative;
width: 100%;
height: 100%;
div {
width: 100px;
height: 100px;
background-color: #cccccc;
position: absolute;
left: 50%;
top: 50%;
// margin-left: -50px;
// margin-top: -50px;
transform: translate(-50%, -50%); // transform:translate 或者margin设置二者选一
}
}
结果展示
Screen Shot 2020-06-02 at 10.45.50 AM.png
Screen Shot 2020-06-02 at 10.46.05 AM.png
3 position:absolute + cal 定位
<div class="container">
<div class="box">
<div></div>
</div>
</div>
.box {
position: relative;
width: 100%;
height: 100%;
div {
width: 100px;
height: 100px;
background-color: #cccccc;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
}
结果
Screen Shot 2020-06-02 at 10.45.50 AM.png
Screen Shot 2020-06-02 at 10.46.05 AM.png