Is there anything wrong with positioning all eleme

2019-01-23 20:43发布

问题:

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;

Would there by anything wrong, or should I say, would anything break if I was to write:

* {
  position: relative;
}

or perhaps the below example, as these are usually the only elements I require the relative positioning on:

div, navbar, footer, section, aside, header, article {
  position: relative;
}

According to W3schools, all elements are position: static; by default which is positioned according to the normal flow of the page.

"HTML elements are positioned static by default. A static positioned element is always positioned according to the normal flow of the page."

and according to the same source, relatively positioned elements also position according to the normal flow of the page unless overridden with CSS:

"The content of relatively positioned elements can be moved and overlap other elements, but the reserved space for the element is still preserved in the normal flow."

回答1:

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.



回答2:

If you apply position: relative to all elements in the page, you won't be able to use position: absolute efficiently, because you can't position an element to the grandparent and you will probably break in a unpredictable way external plugins/modules that rely on position: absolute.

You may encounter problems with z-index (for example in dropdowns menu), and you'll end up overwriting this behaviour with position: static and position: absolute.



回答3:

As for me using position:relative is not good - because sometimes you need to position elemet relatively browser window and it will give a problem to you. But if you are sure that you wont doing this Go ahead



回答4:

The first thing that jumps to mind and one that we saw in one of our sites recently was that any absolutely positioned elements within those relatively positioned elements will have their position offset from that element.

As an example that would be a problem if you were trying to position to the centre of the body.