I am struggling to understand why I need to add position: relative;
for a container element when its child element is positioned absolutely (i.e. position: absolute;
). Let me explain by example.
Sample HTML Code:
<ul>
<li>...</li>
<li id="parent">
<a href="#">Menu</a>
<div id="child">...</div>
</li>
<li>...</li>
<li>...</li>
</ul>
Consider that the code represents a horizontal menu. Which appears somewhat like this:
The problem is when the value of the position
property of #parent
is default (i.e. position: static;
), its width increases with the width of the #child
even though the child element is positioned absolutely, which shouldn't be happening as #child
is now out of the flow due to position: absolute;
.
Everything falls in place, when I use position: relative;
on #parent
i.e. its width stays the same, no matter what the size of the #child
.
What am I missing here? Why do I need to use position: relative;
for something that (I presume) should be the default behavior?
UPDATE: I've created a fiddle to better explain my point. Please take a look.
Steps to reproduce the problem:
In the preview of the fiddle, click on the "Channels" menu, which should slide out its hidden menu-item.
Now, hit F12 key in your browser (Chrome, Safari, or Firefox with Firebug installed), use the inspect tool to inspect the "Channels" menu.
That should immediately point you to the relevant HTML code in the "Elements" tab of the now open Dev Tools or Firebug pane.
Look for the first instance of
<li class="float-left top-menu">
inside<ul id="top-navbar">
and hover your mouse over that line. It should show you something like this:
Why is the blue indicator box (i.e. the menu) that big when it should be the size of the red border? Get the idea of what I am saying now?
Now, apply position: relative;
on the li
(i.e. li.float-left.top-menu { position: relative; }
and see the difference for yourself.)