1.transform变形(需先知道宽高)
.outer {
height: 100vh;
}
.wrapper {
width: 80%;
height: 60%;
background: rgb(185, 59, 59);
transform: translate(12.5%, 33%);
}
<div class="outer">
<div class="wrapper">
</div>
</div>
translate具体算法:
将子元素的宽和高设置为百分数,如宽设置为 80%,则需要向 X 轴偏移 10% 那么 translateX 为10/80 = 0.125,即 12.5%;如果高设置为 60%,则需要向 Y 轴偏移 20%,那么 translateY 为20/60 = 33%
2.flex布局
.outer {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.wrapper {
/* width: 200px;
height: 200px; */
background-color: aquamarine;
}
<div class="outer">
<div class="wrapper">
aaa
</div>
</div>
3.position:fixed布局
.outer {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.wrapper {
width: 50%;
height: 30%;
margin: auto;
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: aquamarine;
}
<div class="outer">
<div class="wrapper">
aaa
</div>
</div>
4.position:fixed和transform使用
.outer {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.wrapper {
width: 50%;
height: 30%;
position: fixed;
left: 50%;
top: 50%;
background-color: aquamarine;
transform: translate(-50%,-50%);
}
<div class="outer">
<div class="wrapper">
aaa
</div>
</div>
5.补充
1.translate百分比根据什么计算
translate是将元素平移 百分比是按照自身宽高计算的 若是宽100px 而是50%的话则移动50px