在没有容器溢出的情况下更改绝对元素的位置
Changing position of absolute element without container overflow
这可能是一个显而易见的问题,但是如何使具有绝对位置的元素在正确移动其位置时不会溢出其容器?我知道我可以将其更改为相对位置或将其移动 99%,但对于我的项目来说,这不会到期。我尝试使用边距、填充、对象匹配,但都没有成功。感谢您的帮助
var green = document.getElementById('green');
function myFunct() {
green.style.right = '100%';
}
h1 {
position: relative;
width: 80%;
height: 100px;
margin: auto;
background-color: red;
}
#green {
position: absolute;
right: 0px;
height: 100px;
background-color: green;
width: 20px;
}
<h1>
<div id = 'green'></div>
</h1>
<button onclick="myFunct()">FindHighScore</button>
使用CSScalc()
var green = document.getElementById("green");
function myFunct() {
green.style.right = "calc(100% - 20px)";
}
或者,应用 left: 0
和 right: auto
(重置)
var green = document.getElementById("green");
function myFunct() {
green.style.left = "0";
green.style.right = "auto";
}
顺便说一下,<div>
不应该在 <h1>
标签中。
您可以在父容器中将 overflow
设置为 hidden
。
<h1>
允许的内容是Phrasing content
var green = document.getElementById('green');
function myFunct() {
green.style.right = '100%';
}
div:not(#green) {
position: relative;
width: 80%;
height: 100px;
margin: auto;
background-color: red;
overflow: hidden;
}
#green {
position: absolute;
right: 0px;
height: 100px;
background-color: green;
width: 20px;
}
<div>
<div id='green'></div>
</div>
<button onclick="myFunct()">FindHighScore</button>
这可能是一个显而易见的问题,但是如何使具有绝对位置的元素在正确移动其位置时不会溢出其容器?我知道我可以将其更改为相对位置或将其移动 99%,但对于我的项目来说,这不会到期。我尝试使用边距、填充、对象匹配,但都没有成功。感谢您的帮助
var green = document.getElementById('green');
function myFunct() {
green.style.right = '100%';
}
h1 {
position: relative;
width: 80%;
height: 100px;
margin: auto;
background-color: red;
}
#green {
position: absolute;
right: 0px;
height: 100px;
background-color: green;
width: 20px;
}
<h1>
<div id = 'green'></div>
</h1>
<button onclick="myFunct()">FindHighScore</button>
使用CSScalc()
var green = document.getElementById("green");
function myFunct() {
green.style.right = "calc(100% - 20px)";
}
或者,应用 left: 0
和 right: auto
(重置)
var green = document.getElementById("green");
function myFunct() {
green.style.left = "0";
green.style.right = "auto";
}
顺便说一下,<div>
不应该在 <h1>
标签中。
您可以在父容器中将 overflow
设置为 hidden
。
<h1>
允许的内容是Phrasing content
var green = document.getElementById('green');
function myFunct() {
green.style.right = '100%';
}
div:not(#green) {
position: relative;
width: 80%;
height: 100px;
margin: auto;
background-color: red;
overflow: hidden;
}
#green {
position: absolute;
right: 0px;
height: 100px;
background-color: green;
width: 20px;
}
<div>
<div id='green'></div>
</div>
<button onclick="myFunct()">FindHighScore</button>