在chrome浏览器中,当将边框添加到父固定元素时,其绝对子元素位置会发生变化,具体取决于父元素的外边界,但在Edge和Firefox浏览器中不会发生变化。
document.getElementById('add').addEventListener("click",()=>{
document.getElementById('fixed').classList.add("border");
})
document.getElementById('delete').addEventListener("click",()=>{
document.getElementById('fixed').classList.remove("border");
})
.fixed{
position: fixed;
width: 400px;
height: 400px;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
background: red;
}
.absolute{
position: absolute;
width: 100px;
height: 30px;
top: 30px;
right: 30px;
background: yellow;
}
.border{
border:8px solid green;
}
<html>
<head>
<title>TSET</title>
</head>
<body>
<div class="fixed" id="fixed">
<div class="absolute" ></div>
<button id="add">add</button>
<button id="delete">delete</button>
</div>
</body>
</html>
您可以通过确保重新计算排名来解决此问题您也可以使用
right:0.000001px;
如果您在两个不同的规则中加点写宽度。但是我认为这比下面的解决方案更丑陋]document.getElementById('add').addEventListener("click",()=>{ document.getElementById('fixed').classList.add("border"); }) document.getElementById('delete').addEventListener("click",()=>{ document.getElementById('fixed').classList.remove("border"); })
.fixed{ position: fixed; width: 400px; height: 400px; top: 0; left: 0; bottom: 0; right: 0; margin: auto; background: red; } .absolute{ position: absolute; width: 100px; height: 30px; top: 30px; right: 30px; background: yellow; } .border{ border:8px solid green; } .fixed{ position: fixed; width: 400px; height: 400px; top: 0; left: 0; bottom: 0; right: 0; margin: auto; background: red; } .absolute{ position: absolute; width: 30px; height: 30px; top: 0px; right: 0px; background: yellow; } .border{ border:8px solid green; } .border .absolute{ left:calc(100% - 30px); }
<html> <head> <title>TSET</title> </head> <body> <div class="fixed" id="fixed"> <div class="absolute" ></div> <button id="add">add</button> <button id="delete">delete</button> </div> </body> </html>