0

Say there are some "absolutely positioned" elements whose coordinates(unit: %) are grabbed with Ajax.

Sometimes a certain edge of them sticks out of the screen, like when they are too right or too top. I cannot position them as right: 0 because their parent element is already "absolutely positioned", hence that won't work.

How can one prevent an element from ever sticking out of screen, given its direct parent element is not the document.body?

Jason Lam
  • 1,342
  • 3
  • 14
  • 17

1 Answers1

0

Have you tried using the css property overflow: hidden on the body? For example:

.box {
  border: 1px solid #222;
  width: 300px;
  height: 300px;
  overflow-y: hidden;
  overflow-x: scroll;
}
<div class="box">
  <img src="http://placehold.it/450x150" alt="" />
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae suscipit, autem magnam ab. Possimus perferendis officiis doloremque impedit quia quos labore optio quas cum incidunt. Blanditiis dicta, sunt numquam quos.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae suscipit, autem magnam ab. Possimus perferendis officiis doloremque impedit quia quos labore optio quas cum incidunt. Blanditiis dicta, sunt numquam quos.</p>
</div>

If you want content to never move out of range of the body, you'd need to grab that element's position relative to the window and not allow it to move beyond its borders (for example, any given element's left position relative to the body shall never be more than windowWidth-currentElementWidth). You can find more on this here

Community
  • 1
  • 1
sgarcia.dev
  • 5,671
  • 14
  • 46
  • 80
  • Yet knowing the element's left position relative to body is one thing, force it to not move beyond the body is another thing. I can get `element.getBoundingClientRect().left` but I cannot set it, because it's readonly. Setting `element.style.left` won't work because its parent element is also `position: absolute`. – Jason Lam Jun 23 '16 at 06:41