Skip to main content

Positions Relative and Absolute - CSS

A visual representation of CSS positions relative and absolute, the black container is on position: relative and position: absolute for the rest of the coloured boxes.

DEMO

position: absolute;
top: 0;
left: 0;
position: absolute;
top: 0;
right: 0;
position: absolute;
bottom: 0;
left: 0;
position: absolute;
bottom: 0;
right: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

HTML

<div class="container-box">
  <article class="top-left">
    position: absolute;<br>
    top: 0;<br>
    left: 0;
  </article>
  <article class="top-right">
    position: absolute;<br>
    top: 0;<br>
    right: 0;
  </article>
  <article class="bottom-left">
    position: absolute;<br>
    bottom: 0;<br>
    left: 0;
  </article>
  <article class="bottom-right">
    position: absolute;<br>
    bottom: 0;<br>
    right: 0;
  </article>
  <article class="centered">
    position: absolute;<br>
    top: 50%;<br>
    left: 50%;<br>
    transform: translate(-50%, -50%);
  </article>
</div>

CSS

.container-box {
  width: 100%;
  height: 300px;
  background: black;
  position: relative;
}
.container-box article {
  padding: 0.5em;
  position: absolute;
  width: 150px;
  line-height: normal;
  font-size: small;
}
.container-box  article.top-left {
  background: LightBlue;
  top: 0;
  left: 0;
}
.container-box  article.top-right {
  background: Gold;
  top: 0;
  right: 0;
}
.container-box  article.bottom-left {
  background: Ivory;
  bottom: 0;
  left: 0;
}
.container-box  article.bottom-right {
  background: LightGreen;
  bottom: 0;
  right: 0;
}
.container-box  article.centered {
  background: PaleTurquoise;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Comments