You better be absolutely sure

19.03.05 #lessons

How many times have you been tasked with positioning an element on a page and end up in this cycle...

An image

🤦‍♂️, right ? Let's recreate this face palming scenario and try to understand what might be happening in these situations. Let's start with this markup...

<div class="container">
  <div class="a">A</div>
  <div class="b">B</div>
</div>

...and this CSS...

.container {
  border: 1px solid black;
  position: relative;
  width: 100px;
}

Which will result in the following...

A
B

Now here's your task. Move B to the far right of the page outside of its containing black rectangle. Your first attempt might go as follows...

.b {
  position: absolute;
  right: 0;
}

You've declare a rule for the B element in which you are saying it's now an absolutely positioned position: absolute element that will go to the far right right: 0 of the page.

And the result...

A
B


Huh?

B should have moved to the far right of the page, right ? Noooope. You see, absolutely positioned elements are constrained to the confines of its closest ancestor element with a position property declared. In this case the .container rule has a position: relative; statement in it meaning that B will only move about within the limits of the black rectangle. Side note: The black rectangle no longer appears around the B element as well because its no longer considered to be part of the normal document flow as a result of its position: absolute; property.

... now what ?

If you want the B element to move to the far right of the page you need the element to exist outside of the .container in a place where an ancestor elements are not using the position property in any style definitions. OR, in this very simple example, take away the position property from the .container style (which was only there for demonstration purposes) to end up with this...

.container {
  border: 1px solid black;
  width: 100px;
}
.b {
  position: absolute;
  right: 0;
}

With the html markup we started with you would then see...

A
B

The element is now at the far right! 👀

... and finally

The solution presented here hopefully sheds some light on explaining the reason you may have been stuck trying the same thing in a different scenario. The better solution here is to use features like flex layouts and grid layouts to help you control positioning of elements. If you don't or can't use those layouts then always be aware of what elements in the html define a position property in their styles and you'll have a better idea of what positioning your element will result in.

~Zano

Last Updated: 3/20/2019, 1:01:13 AM