the weird behaviour of multi level horizontal navigation menu when We remove "position:relative"?

The below one is My code for multi-level horizontal navigation menu and it is working fine https://codepen.io/siva-charan/pen/zYmzwOM My doubts are : For the below code : https://codepen.io/siva-charan/pen/vYVZmyG (1) When I am removing “position:relative” on main menu,it is behaving like in the below output image.Why is it behaving like this(first image)? (2) When I am mouse-hovering on the first level drop-down menu(i.e. on two.three) and without “position:relative” on outer menu,the output is behaving like as shown in the below image.Why is it behaving like this(second image)?
In this some of the list items are displaying horizontally(two.three.one and two.three.two) and (two.three.three and two.three.four) and some list items are displaying vertically.Why is the outpout behaving like this?
1 Reply
Chris Bolson
Chris Bolson11mo ago
This is all related to the way positioning works. If you don't define any positions, by default the elements will have a position of "static" and show in their "natural" position within the flow. In the case of nested "ul"s these will appear relative to their parent "li" When you give an element a position "absolute", "relative" or "sticky" it will be positioned in relation to its nearest parent, or grandparent with its position defined. If none of its ancestors have a position defined this will default to the body tag. It is important to note that for "absolute" and "relative" positioned elements, unless you specifically defined the position using "top", "right", "bottom", "left" or by using the shorthand "inset", the element will still be placed in it's natural position within the flow, it won't magically be moved to a different position (unlike "fixed" and "sticky") As you have defined float: left on all of your "li", they are displaying in a row within the available width. On the top level UL the width is 100% so the "li"s show in a horizontal row. On lower levels, as all your "li"s have a defined width of 100px, their children are restricted to a width of 100px which is why the nested items appear as vertical lists. However, as you removed position: relative from the "li"s but they still have "position: absolute; they now are not restricted to their parents width so can spread out horizontally. This is why they switched from being a vertical list to a horizontal list. So why is the third level being shown vertically? This is due to the fact that as the second level "ul" has position: absolute` so now it's children are restricted to its constraints (position and width) As to why the third level "ul" is appearing on top of the previous level item (two.four) this is because in this case you have moved its natural position with
margin-left: 100px;
top: 0px;
margin-left: 100px;
top: 0px;
A bit of a tricky one to explain, I hope I got it all right and don't end up confusing you 😛