How to position element just beyond the left edge of the viewport?
Asked Answered
S

2

5

I have an element whose width is either a fixed px value or a percentage. I want the right side of its bounding box to be at x coordinate −1 of the screen (or viewport), so its right side is touching the left side of the screen — the element would become invisible by this.

Is there a value I can use for the CSS right or left property that works for both percentages and fixed px widths or is there some other way to achieve this?

Spermatozoon answered 15/7, 2015 at 2:5 Comment(1)
show relevant code of what you've attempted, preferably with a jsfiddle/stack snippetGrapher
H
8

This set of CSS rules works for that:

/* These rules position the element just beyond the left edge of the viewport. */
.positioned {
  position: absolute;
  left: 0;
  transform: translateX(-100%);
}

/* You can open your developer tools (Right Click → Inspect Element) and change the `-100%` from above to see this box. */
.positioned {
  width: 100px;
  height: 100px;
  background: rebeccapurple;
  padding: 4px;
  color: white;
}
<div class="positioned">
  I’m on the left.
</div>

position: absolute and left: 0 place the element at the left edge, but within the viewport. Then transform: translateX(-100%) is the rule that moves your element to the left exactly by its width.

This works because, if the arguments of translate, translateX, or translateY are percentages, then these percentages relate to the element’s width and height. In the case of other properties like left or right, they relate to the parent’s width and height. Therefore, left and right cannot be used in all circumstances for this — relative or fixed width —, which is why the answer to your original question is: no, there is no value for those two properties to achieve this. There may be some form of trickery to achieve this, but CSS3’s transform functions (or individual — albeit less compatible — properties) make this easy.


If you run the snippet you should see nothing. If you use the browser console (dev tools) (hit F12) and inspect the result of the snippet and find the <div class="positioned">, you’ll see this:

The bounding box of the <div> can be seen just to the left of the snippet result.

Heyde answered 15/7, 2015 at 2:16 Comment(0)
D
0

Try this:

.fixed {
    position: fixed;
    top: 1em;
    left: 1em;
}
Door answered 15/7, 2015 at 2:13 Comment(1)
This fits the title of the question, but not the description that the object should be hiding off the left hand side of the screen.Caty

© 2022 - 2024 — McMap. All rights reserved.