相对定位所有元素有什么问题吗? [英] Is there anything wrong with positioning all elements relatively?

查看:124
本文介绍了相对定位所有元素有什么问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我发现自己附加一个类给一个元素只是给它 position:relative; ,以便我可以使用 position:绝对的;

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;
}

或者下面的例子,因为这些通常是唯一的元素我需要相对位置:

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

根据W3schools,所有元素 position:static ;

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


HTML元素位于静态静态定位的
元素总是根据
页面的正常流程定位。

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

和根据相同的源,相对定位的元素也根据页面的正常流动定位,除非被CSS覆盖:

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


推荐答案

是的,是的。如果你尝试定位一个元素 absolute ,它相对于最接近的祖先,它有一个CSS position static

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.

如果每个元素都具有 position:relative ,这将是直接父。

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

但您可能希望将绝对元素相对于DOM树中的元素相对放置,或者绝对在页面主体上。

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.

在某些时候,你会遇到你不能完全控制HTML的情况。然后你会看到,设置所有相对是适得其反的。

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.

一个例子可能是phat层菜单。你有一层 .menu 类中层的层次 ul li 元素。这应该相对于 .menu 元素的位置。您可能不想在这里更改DOM树。

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.

这篇关于相对定位所有元素有什么问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆