Search code examples
javascripthtmlcsspositionabsolute

Changing position of absolute element without container overflow


Maybe an obvious question but how do I make an element with a absolute position not overflow its container when moving it's position right? I know I could change it to relative position or move it 99% but for my project that won't due. I tried using margins, padding, object-fit, all with no success. Thanks for any help

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>


Solution

  • Use CSS calc()

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

    Or, apply left: 0 and right: auto (reset)

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

    A <div> should not be in a <h1> tag by the way.