Course Content
Advanced CSS Techniques
Advanced CSS Techniques
Absolute Positioning
Using absolute positioning removes the element from the default document flow, allowing other neighboring elements to fill the gap. The element's top
, left
, bottom
, and right
positioning values are calculated relative to its nearest ancestor with non-static positioning. If there is no such ancestor, the values are determined based on the borders of the <body>
element.
Generally, we are interested in using absolute positioning in combination with relative positioning because we need to position an element respectively to another element in the document flow.
Consider the following example. The task is to set the city name (a <span>
element with the description
class) in the top right corner of the city card (a <div>
element with the card
class). Pay attention to the position property for the different elements.
index
index
index
In this example, the .description
elements are positioned absolutely inside the .card
elements, thanks to the position: relative;
applied to the .card
. This positioning places the city names in the top right corner of each card.
We can move the element respectively to another element. How does it work? We need to apply position: relative;
to the element which is the ancestor to the element which we would like to position absolutely. In another case, the element will be positioned respectively to the <body>
element.
Note
When specifying the
top
,left
,right
, andbottom
properties for the absolutely positioned element, the browser calculates them starting with the relatively positioned element's borders. This can be seen as applying a margin to the child element inside the parent element.
Thanks for your feedback!