Is there anything wrong with positioning all elements relatively?

后端 未结 4 1072
天命终不由人
天命终不由人 2020-12-16 06:35

Often I find myself attaching a class to an element just to give it position: relative; so that I can position it\'s children using position: absolute;

4条回答
  •  天涯浪人
    2020-12-16 06:58

    Yes, it is. If you try to position one element absolute it is positioned relatively to the closest ancestor, which has a CSS position other than static.

    If every element has position:relative, this would be the direct parent.

    But you might want to position the absolute element relatively to an element further up in the DOM tree or maybe absolutely on the page body.

    At some point you will have the situation where you are not in full control of the HTML. Then you will see, that it is counterproductive to set everything relative.

    An example might be a phat layer menu. You have the layer inside a .menu class somewhere deep in the jungle of hierarchical ul li elements. This should be positioned relative to the .menu element's position. You might not want to change the DOM tree here.

提交回复
热议问题