In CSS positioning, absolutely and fixed elements are placed relative to the viewport or the nearest positioned parent element, respectively. However, understanding their behavior can sometimes be challenging.
When an element's position property is set to auto or static, it assumes the static position. This means it will be placed as if its position were static. In this case, the element's position is calculated based on its margins, borders, padding, and content.
In your first code snippet, the gray box has an absolute position. However, the parent container (
In your second code snippet, you have moved the gray box to the second position within the container. However, it is still not in the top-left corner because the container has a padding: 40px 20px; rule, which affects the hypothetical static position of the element. The gray box will be positioned relative to this adjusted static position.
To correctly position absolute or fixed elements, it is crucial to understand the concept of the static position and how it is calculated based on margins, borders, padding, and content. This knowledge enables you to anticipate the behavior of these elements within different positioning contexts.
The above is the detailed content of Why Aren't My Absolutely or Fixed-Positioned Elements Where I Expect Them?. For more information, please follow other related articles on the PHP Chinese website!