'why is this snippet working when the positions should be the other way around?
<h1 id='title2'>news,tips and more!!</h1>
<button class="button" type="button">Contact us!</button>
#title2{
position: absolute;
bottom: 100px;
right: 560px;
color: greenyellow;
}
.button {
background-color: greenyellow;
color: black;
position: relative;
bottom: 97px;
left: 200px;
}
I'm just wondering why this works when position absolute you can only make it work by having position relative as parent?
Solution 1:[1]
You've misunderstood the relationship between position: absolute and position: relative.
When you absolutely position an element, it is positioned with respect to its nearest ancestor (not parent) which is positioned.
An element is positioned if the value of its position property is not static.
If there is no such element, then it is positioned with respect to the browser viewport. (This is what is happening in your example).
position: relative is the only positioning scheme which leaves the element in normal flow. If there is no left, top, etc property then it won't change how that element is laid out at all.
This makes it a popular way to make an element positioned so that a descendant that is absolutely positioned is positioned with respect to it.
Since you almost never want to position an element with respect to the viewport (and if you do then you might want to think about grid or flexbox layouts instead of positioning) it is usual to have a close ancestor that is position: relative to control where the absolutely positioned element goes.
i.e. it is a useful tool that you will want to use in 9/10 cases to get the effect you want, not a requirement.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin |
