When to use position absolute or relative in CSS?

I know that an element inside with position absolute does not respect the limits of the parent div and that relative respects, and theoretically positions itself in relation to itself.

My doubts basically are:

  1. An element absolute stops respecting only the boundaries of the parent div, but aligns with the previous div or just the body?

  2. When and why use an element relative inside a absolute (or vice versa)?

  3. When it is appropriate use one or the other?

Author: bfavaretto, 2014-10-27

2 answers

This confuses many people because the property position defines two things: how the element behaves in relation to its ancestors in the hierarchy, and how its descendants may behave in relation to it.

The principles are:

  1. Both position: relative and position: absolute determine positioning contexts for the descendants of the element.

  2. Elements with position: absolute are positioned relative to the nearest positioning context. By example:

    <div style="position: relative">
        <div>
            <div style="position: absolute"></div>
        </div>
    </div>
    

    The third <div> can be positioned with top and left relative to the outermost. If no positioning context is found by moving up the hierarchy, the element would be positioned relative to <body>.

  3. Elements with position: absolute do not take up space in any of the Ascenders until the placement context. Considering the example above, it is as if the inside div does not exist, both for the middle one, and for the outside one. It does not take up space within the others, it does not influence their height or width. It is said to be removed from the document rendering stream.

  4. Elements with position: relative take up space in their Ascenders. They can be shifted from their expected position with top and left, but this shift does not influence other elements at the same level of the hierarchy or above. For others, it is as if he is always always in the expected position. But visually it may be out of place. By example:

    <div style="position: relative">
        <div style="height: 100px; background: red; position: relative; top: 50px"></div>
        <div style="height: 100px; background: blue"></div>
    </div>
    

    The red div is 50px from the top of the container, and over the top half of the Blue div. That is, it was shifted 50px from its expected position, but this did not move the Blue div from place, it continues to "think" that the red one is where it should be. This is why it is said that elements with position: relative are positioned "in relation to themselves"; the reference for the displacement is always the element itself (and not the container), and for the other elements it is as if it had not been offset.

With these principles, do experiments on how the elements behave. If you don't want an element to leave its "natural" position, don't put position: absolute in it. But it can be useful to use position: relative so that the elements within IT position themselves relative to it.

 43
Author: bfavaretto, 2014-10-27 13:49:30

Definition

The CSS property position it defines alternative rules for positioning elements, having been designed to be useful in creating animations via script .

It is usually used in conjunction with other properties that help move the element or control its position in the element stack:

  • top, right, bottom e left:

    These are used to assign a distance in order to displace the element.

  • z-index:

    Specifies the z-order (position in the element stack) of an element and its heirs. When the elements overlap, the value of z-index determines which element covers the other.

Placement types

There are four values for the property position where each assigns a very element-specific behavior in relation to the document flow:

  • Static: position:static

    Is the default value in the elements, where the auxiliary properties for controlling the positioning or controlling the position in the stack have no effect.

    Static element illustration

        .estatico{
              position:static;
              top:20px;
              left:20px;
            }
            .quadrado{
              width:60px;
              height:60px;
            }
            .vermelho{
              background-color:red;
            }
            .verde{
              background-color:green;
            }
            .azul{
              background-color:blue;
            }
        <div class="quadrado verde"></div>
        <div class="quadrado vermelho estatico"></div>
        <div class="quadrado azul"></div>
  • Relative: position:relative

    The element is positioned relative, that is, it is in its place relative to the flow of the document, but can be moved by making use of the auxiliary properties top and left. Even when shifted, its place in the document flow is preserved.

    Relative element illustration

.quadrado{
  width:60px;
  height:60px;
}
.vermelho{
  background-color:red;
}
.verde{
  background-color:green;
}
.azul{
  background-color:blue;
}
.relativo{
  position:relative;
  top:20px;
  left:20px;
}
<div class="quadrado verde"></div>
<div class="quadrado vermelho relativo"></div>
<div class="quadrado azul"></div>
<p>Repara que o quadrado vermelho foi deslocado para o lado e para baixo mas o seu espaço "normal" está presente como se o elemento estivesse naquela zona vazia.</p>
  • Absolute: position:absolute

    The element is positioned absolutely relative to the document flow, but relative to its nearest ancestor that is also positioned or relative to the document.

    Unlike an element with a relative position, an absolutely positioned element leaves no space in the document flow. An absolutely positioned element is being moved up the document flow, as if placed on a top element layer. The similarity of what happens when we use z-index.

    Can be shifted by making use of the auxiliary propertiestop, right, bottom and left, where they indicate the distance to be between the same and the nearest ancestral element that is positioned.

    Illustration absolute element

.quadrado{
  width:60px;
  height:60px;
}
.vermelho{
  background-color:red;
}
.verde{
  background-color:green;
}
.azul{
  background-color:blue;
}
.absoluto{
  position:absolute;
  top:20px;
  left:20px;
}
<div class="quadrado verde"></div>
<div class="quadrado vermelho absoluto"></div>
<div class="quadrado azul"></div>
<p>Repara que o quadrado vermelho foi deslocado para o lado e para baixo mas o seu espaço "normal" não está presente. O elemento está de facto por cima dos restantes elementos, deixando de estar no fluxo normal do documento.</p>
  • Fixed: position:fixed

    A fixed element is positioned relative to the viewport, that is, relative to the screen. It also leaves no space for the element in the document flow.

    Can be shifted by making use of the auxiliary properties top, right, bottom and left, where they indicate the distance between the same and the screen.

    If there is page scroll ( scroll ), the element will always be in the same place relative to the screen, not keeping up with the page scroll.

    When printed, a fixed element is always in the same place on all pages.

    Fixed element illustration

.quadrado{
  width:60px;
  height:60px;
}
.vermelho{
  background-color:red;
}
.verde{
  background-color:green;
}
.azul{
  background-color:blue;
}
.fixo{
  position:fixed;
  top:20px;
  left:20px;
}
.relativo{
  position:relative;
}
<div class="quadrado verde"></div>
<div class="quadrado vermelho fixo"></div>
<div class="quadrado azul"></div>
<p><small>Se olharmos para o quadrado vermelho, parece estar posicionado de forma absoluta. <em>(ver exemplo anterior para melhor entendimento)</em>.</small></p>

<div class="relativo">
      <div class="quadrado verde"></div>
      <div class="quadrado vermelho fixo"></div>
      <div class="quadrado azul"></div>
      <p><small>Repara que este segundo grupo de quadrados está dentro de um elemento com posição relativa mas o quadrado vermelho não quer saber disso e está posicionado em relação à tela tendo ficado por cima do primeiro quadrado vermelho.</small></p>
</div>

Behaviors

Positioned elements introduce two behaviors to the document, first the way the element itself will behave, second, the way its descending elements will behave.

In short, an element is always positioned relative or absolute from its nearest ancestor that is positioned. We have seen above that static elements are relative to the screen and not to their ancestors.

This also tells us that any non-static element will serve as a basis for the positioning and displacement of their descendants.

For example:

  • The element .filho will be positioned absolutely relative to the element .pai:

    .pai{
      position:relative;
    }
    .pai .filho{
      position:absolute;
    }
    
  • The element .filha will be positioned relative to the element .pai:

    .pai{
      position:relative;
    }
    .pai .filha{
      position:relative;
    }
    
  • The element .filha will be positioned relative to the element .pai and the element .filho will be positioned relative to the element positioned absolutely with respect to element .pai:

    .pai{
      position:absolute;
    }
    .pai .filha{
      position:relative;
    }
    .pai .filho{
      position:absolute;
    }
    
  • The element .neto will be positioned absolutely relative to the element .pai:

    .pai{
      position:absolute;
    }
    .pai .filha{
      position:static;
    }
    .pai .filha .neto{
      position:absolute;
    }
    
  • The element .neto will be positioned absolutely relative to the screen:

    .pai{
      position:absolute;
    }
    .pai .filha{
      position:static;
    }
    .pai .filha .neto{
      position:fixed;
    }
    
 43
Author: Zuul, 2014-10-27 06:48:33