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?
An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element. A fixed element does not leave a gap in the page where it would normally have been located.
We can make the dialog div be position relative to the parent div by first making it a child of the parent div and then setting the parent position to relative. The parent is set to relative position and the dialog has absolute position. Now the dialog div is rendered over the parent div.
static. The element is positioned according to the normal flow of the document. The top , right , bottom , left , and z-index properties have no effect. This is the default value.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With