CSS - Absolute Positioning

CSS - Absolute Positioning

Today, I helped a fellow student in my coding bootcamp. The main thing I took away from it the behavior of absolute positioning in CSS.

She wanted to position a label over an image - a sort of banner that laid across the image to give it a name and some flare. Like this: Screenshot 2022-03-12 001422.png

So we created a container element with another element within it that we will control the position of. The HTML looked something like this:

<div class="container">
     <div class="move-me">
          <p>
               Image Name Here
          </p>
     </div>
</div>

Simple enough.

To painlessly position a child element within a parent element, we needed to add the "position: absolute" property to the child element. Then, we simply position the child element with any number of CSS properties (top, right, bottom, left, etc.) to get it in the right spot.

.move-me {
     position: absolute;
     left: 0;
     top: 50%;
}

This is where it gets interesting. If we ONLY, add the absolute positioning property to the child element, we don't get what we expected. The parent element (the "container" class, in this example), needs to have the "position: relative" property.

That's because the "position: absolute" property only gives the freedom we expected inside the nearest positioned ancestor. Otherwise, the element defaults to being relative to the document body. So we add relative positioning to the parent/container element.

Our CSS looked something like this:

.container {
     position: relative;
}

.move-me {
     position: absolute;
     left: 0;
     top: 50%;
}

To take full advantage of the flexibility of "position: absolute" we needed to add "position: relative" to the container element. Something worth remembering.

Here is the GitHub repository to see the CSS in action:

Check out my version of the deployed site here:

Thanks for reading, Robert