When to use Absolute or relative position in CSS?

Asked

Viewed 40,509 times

49

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

My doubts are basically:

  1. An element absolute no longer respects only the boundaries of the parent div, but aligns with the previous div or only with the body?

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

  3. Where it is appropriate to use one or the other?

  • 6

    Excellent question, very common and to my knowledge no one had asked this on the site yet. I took the liberty of editing to make the question more neutral, more useful to other people with the same question.

  • 2

    Yes, +1. I literally learned this last week. And now with these very detailed answers, knowledge is consolidated 100%. . . . [note-to-author] ropbla, please check the history of the issues that are made in your questions, so you do not make the same mistakes in the following questions. Thanks!

2 answers

44

Definition

The property of CSS position sets 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 stack of elements:

  • top, right, bottom and left:

    They are used to assign a distance in order to move the element.

  • z-index:

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

Types of positioning

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

  • Static: position:static

    It is the default value in the elements, where the auxiliary properties to control the positioning or control the position in the stack has no effect.

    Ilustração elemento estático

        .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 in a relative way, that is, it is in its place in relation to the document flow, but can be moved by making use of the auxiliary properties top and left. Even when displaced, its place in the flow of the document is preserved.

    Ilustração elemento relativo

.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 who is also positioned or relative to the document.

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

    Can be displaced by making use of auxiliary properties top, right, bottom and left, where they indicate the distance between it and the nearest ancestor that is positioned.

    Ilustração elemento absoluto

.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, i.e., in relation to the screen. It also leaves no space for the element in the document flow.

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

    If page scrolling exists (scroll), the element will always stay in the same place in relation to the screen, not following the page scrolling.

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

    Ilustração elemento fixo

.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>

Behaviours

The 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 saw above that static elements are relative to the canvas 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 your descendants.

For example:

  • The element .filho will be positioned absolutely in relation 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 absolutely in relation to the element .pai:

    .pai{
      position:absolute;
    }
    .pai .filha{
      position:relative;
    }
    .pai .filho{
      position:absolute;
    }
    
  • The element .neto will be positioned absolutely in relation 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


This confuses a lot of 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. So much position: relative how much position: absolute determine positioning contexts for the descendants of the element.

  2. Elements with position: absolute are positioned relative to the closest positioning context. For 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 most external. If no context of positioning is found going up the hierarchy, the element would be positioned relative to the <body>.

  3. Elements with position: absolute do not occupy space in any of the ascendants until the context of positioning. Considering the above example, it is as if the div from within did not exist, both for the middle, and for the outside. It does not occupy space within the others, it does not influence their height or width. It is said that it is removed from the document rendering flow.

  4. Elements with position: relative take up space in their ascendants. They can be moved from their position expected 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 in the expected position. But visually he may be displaced. For 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 on the top half of the blue div. That is, it was moved 50px from its expected position, but this did not move the blue div of place, she continues "thinking" that the red is where it should be. That is why it is said that the 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 moved.

With these principles, experiment on how the elements behave. If you do not want an element to leave its "natural" position, do not position: absolute on it. But it may be useful to use position: relative so that the elements within it position themselves in relation to it.

  • @bfavarretto, although reading and rereading his answer I still could not understand how a relative/Absolute element behaves within another relative/Absolute. All I know since I started studying is that an Absolute in relative positions itself from the relative and not before it. I still don’t know why. I think I have a "mental block".

  • @ropbla9 I don’t even know what else to explain... The examples of Zuul’s answer are no longer clear to you? Let me know when you’re online, if I can chat.

  • @bfavaretto I’ll delete my comment here, I was in a doubt: Se nenhum contexto de posicionamento for encontrado subindo a hierarquia, o elemento seria posicionado em relação ao <body>. following this line of reasoning here at Fiddle my debt vermelha should be in the upper left corner, div green,or am I wrong? Could you explain to me why not? :)

  • @Marconi Porque top and left red div are not set. If they are, they will be relative to the upper left corner of the body.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.