DEV Community

Uzoma Udoma Alex
Uzoma Udoma Alex

Posted on

Div. Positioning (Absolute)

Absolute

This article focuses on position: absolute, however you can read my earlier articles on position: static; and position: relative; to catch up.

The positioning of a div relative to the closest containing element is what distinguishes absolute positioning from relative positioning.

The absolute position can be used with other position properties such as Top, Bottom, Left, and Right to offset the div as desired.

In contrast to position: relative;, position: absolute; totally removes the element from the document flow, and all other elements continue to move as if the div does not exist.

Since the div's movement no longer affects the positioning of other elements, it is now responsible for stacking and overlapping.

Relative is positioned relative to itself or, better still, relative to its original location. In contrast, absolute is positioned relative to the closest parent element.

It's important to keep in mind that there are two elements to be considered using the absolute positioning.

.container {
  border: 1px solid #000;
  position: relative;
}
.box1 {
  width: 100px;
  height: 100px;
  background-color: #f00;
  position: absolute;
  top: 20px;
}
.box2 {
  width: 60px;
  height: 60px;
  background-color: #0003;
}
Enter fullscreen mode Exit fullscreen mode

The above are the CSS settings for an HTML document with two child elements (box1 and box2) and a div (container) acting as their parent div.

The parent div (container) has its position property set to relative; this allows (box1) to be placed absolutely to it.

view Code

Take note of how Box1 has now shifted 20 pixels away from the top of the container div.

Recall that I said we use an absolute position, relative to the nearest parent element.

Box1

What happens when the Parent div isn't positioned relative?
Of course, since the container div is the element's closest parent div, Box1 will still move 20 pixels away from it.

No Position

When the position: relative; property associated with the container div is commented out, the distance between box1 and the container decreases. This is because box1 is now adopting the screen as its parent div.

The position of Box2 will be based on the normal document flow since its position property is not set. It is positioned behind Box 1 causing stacking or overlapping.

In order to manage the overlapping, one can use the CSS property z-index.

Top comments (0)