fixed定位没有相对与浏览器可视窗口定位问题
今天开发中fix定位的盒子出现了问题,记录一下
问题描述
想要实现的效果:绿色的盒子定位在顶部
实际效果:固定定位的盒子相对于父盒子定位
部分代码:father父盒子居中;son子盒子在父盒子中央;son的子盒子fixbox是固定定位,它的定位出现了问题
<div class="father">
<div class="son">
<div class="fixbox"></div>
</div>
</div>
<style>
/* 使用定位加transform父盒子居中 */
.father {
position: relative;
left: 50%;
transform: translateX(-50%);
width: 50%;
height: 100%;
background-color: skyblue;
}
/* 使用定位加transform子盒子居中 */
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 300px;
height: 300px;
background-color: pink;
}
/* 想让盒子固定定位,想让fixbox固定在顶部 */
.fixbox {
position: fixed;
top: 20px;
width: 50px;
height: 50px;
background-color: greenyellow;
}
</style>
出现的原因
固定定位的父盒子使用了transform,会使具有固定定位的子盒子变为绝对定位
father和son都使用了tramsform,所以fixbox变为了绝对定位
解决方案
1>移动固定定位盒子的位置
可以将固定定位的盒子移到最外面了,比如移到body中
上面例子,允许的情况下,可以将它移出father盒子
2>取消父盒子的tramsform,改用其他办法实现布局
我们不方便移动固定定位的位置,因为固定定位样式时动态的,移动了会影响其他状态下的样式;比如上面的让盒子居中我们可以使用其他方式
定位加margin
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
felx布局
display: flex;
justify-content: center;
align-items: center;
display: flex;
justify-content: center;
align-items: center;