Why is an absolutely positioned element placed by its sibling instead of at the top corner of the page?

前端 未结 2 882
挽巷
挽巷 2021-01-24 00:26

I don\'t understand why my absolutely positioned element appears after my child_static div. I always thought that absolutely positioned elements are taken out of th

2条回答
  •  时光取名叫无心
    2021-01-24 00:38

    I always thought that absolute positioned elements are out of the flow.

    Yes, they are removed from normal flow.

    I don't understand why absolute positioned element appeared after child_static div.

    Just because absolute positioning removes elements from normal flow, it doesn't mean it does alter the position of the elements as well.

    In other words, absolutely positioned elements would be at the same place as they are not positioned absolutely unless their top, left, ... offsets are set.

    So what happens is that they would overlap next sibling elements, because they are not part of document flow anymore.

    For instance have a look at the following example where the gold

    element is covered by absolutely positioned element.

    .parent {
        position: relative;
    }
    
    .child_static {
        height: 20px;
        background: blue;
    }
    
    .child_absolute {
        position: absolute;
        height: 20px;
        width: 100%;
        background: green;
    }
    
    .child_static ~ .child_static {
        background: gold;
    }
    Green
    Blue
    Gold

提交回复
热议问题