HTML absolute element interact with window bounds

Issue

I created a sample to show my problem: jsfiddle

I am using an absolute element (it has auto width and height) and I set it’s position from javascript (style.left and style.top specifically), the problem is it is interacting with the browser window’s bounds. As you see in the example the buttons are not positioned horizontally (if you can’t see try to press the run button), because it is near to the window’s right bound..

How can I solve this? I don’t want this interaction, I want the buttons horizontally at any position, if it is near the bound then clip the invisible part like this:

enter image description here

<html>
<head>

</head>
<body>

<div id="container">
  <button>
  First
  </button>
  <button>
  Second
  </button>
  <button>
  Third
  </button>
  <button>
  Quad
  </button>  
</div>
    
</body>
</html>



#container{
  overflow: hidden;
  position: absolute;
  border: 1px solid gray;
  left: 0;
  right: auto;
}


window.onload=() => {
  const container=document.getElementById("container");
  container.style.left= (window.innerWidth-75)+"px";
}

Solution

window.onload=() => {
  const container=document.getElementById("container");
  container.style.left= (window.innerWidth-75)+"px";
}
#container{

  position: absolute;
  border: 1px solid gray;
  left: 0;
  right: auto;
  display: flex;
}
<html>
<head>

</head>
<body>



<div id="container">
  <button>
  First
  </button>
  <button>
  Second
  </button>
  <button>
  Third
  </button>
  <button>
  Quad
  </button>  
</div>



</body>
</html>
  • add display: flex; on #container class

Answered By – Uttam Nath

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published