Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

html - Is there anything wrong with positioning all elements relatively?

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."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...