【问题标题】:Changing position of absolute element without container overflow在没有容器溢出的情况下更改绝对元素的位置
【发布时间】:2019-07-11 09:49:21
【问题描述】:

也许是一个显而易见的问题,但是如何使具有绝对位置的元素在正确移动其位置时不会溢出其容器?我知道我可以将其更改为相对位置或将其移动 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>

【问题讨论】:

  • 标签不能放入

    标签

标签: javascript html css position absolute


【解决方案1】:

使用 CSS calc()

var green = document.getElementById("green");

function myFunct() {
  green.style.right = "calc(100% - 20px)";
}

或者,应用 left: 0right: auto(重置)

var green = document.getElementById("green");

function myFunct() {
  green.style.left = "0";
  green.style.right = "auto";
}

顺便说一句,&lt;div&gt; 不应出现在 &lt;h1&gt; 标记中。

【讨论】:

    【解决方案2】:

    您可以在父容器中将overflow 设置为hidden

    &lt;h1&gt; 允许的内容是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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多