I always thought by setting the div to relative and right 0 would position the div all the way to the right, if its parent was 100% width. Apparently I'm wrong and only absolute works like that. So is there no way to make it work with relative?
Asked
Active
Viewed 3.8k times
3 Answers
24
You have to set the parent to be relative, and it's child to absolute positioning.
.parent{
position: relative;
width: 100%;
}
.right{
position: absolute;
width: 200px;
height: 200px;
background: red;
top:0;
right:0;
}
Like here: http://jsfiddle.net/willemvb/n9Vrv/

Willem Van Bockstal
- 2,233
- 1
- 17
- 24
14
There's a way to make it work to a relative.
One way is first to set the parent of the display to inline-flex
.
Next, set the element (child) position:relative; margin-left:auto; right:0;
.
-
3+1 thr actual solution. It even uses `position:relative` on the child element. Huzzah for `flex`. Here’s a fiddle showing the solution: https://jsfiddle.net/tky8q9zt/ – dakab May 15 '17 at 04:39
-
This is a valid solution, the only thing is I didn't need `right: 0` anymore. – leroyjenkinss24 Jul 13 '21 at 19:43
1
So is there no way to make it work with relative?
Correct. Relative positioning is the position offset from where it would be with static positioning.
You need absolute positioning to position with respect to the edges of the containing block.

Quentin
- 914,110
- 126
- 1,211
- 1,335