CSS 相对 + 右侧(或底部)几乎从不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16290943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS relative + right (or bottom) almost NEVER work
提问by Akshay Sharma
I've been writing CSS for quite some time now.
我写 CSS 已经有一段时间了。
I've noticed that
我注意到了
<div style="position: relative; right: 20%; bottom: 20%;">some text</div>
never works!
从不工作!
relative positioning would work with left and top specified but not with right/bottom. Why?
相对定位适用于指定的左侧和顶部,但不适用于右侧/底部。为什么?
A quick fix around this is to use "absolute" instead and specify right/bottom in pixels, but I need a reason.
解决此问题的快速解决方案是使用“绝对”并以像素为单位指定右/下,但我需要一个理由。
Also, correct me if I'm wrong. Irrespective of whether the external container is positioned absolutely or relatively, does it not make much sense to position something "relative" to the boundaries of that container or should elements inside a container always be positioned "absolute"?
另外,如果我错了,请纠正我。不管外部容器是绝对定位还是相对定位,将某些东西“相对于”定位到该容器的边界还是应该始终将容器内的元素定位为“绝对”没有多大意义?
Thank you.
谢谢你。
采纳答案by oomlaut
From Absolute vs. Relative - Explaining CSS Positioning
Relative positioning uses the same four positioning properties as absolute positioning. But instead of basing the position of the element upon the browser view port, it starts from where the element would be if it were still in the normal flow.
相对定位使用与绝对定位相同的四个定位属性。但是,不是将元素的位置基于浏览器视图端口,而是从元素仍在正常流中的位置开始。
回答by user2313440
Relative positioning does work with bottom/right values, just not the way you were expecting:
相对定位确实适用于底部/右侧值,只是不是您期望的方式:
Think about the position values on relative elements as margins, that the surrounding elements simply ignore. The "margins" will always move the element relative to it's previous position in the normal document flow, but remove it from the normal flow at the same time.
将相对元素上的位置值视为边距,周围的元素会忽略这些值。“边距”将始终相对于它在正常文档流中的先前位置移动元素,但同时将其从正常流中删除。
When out of the normal document flow, the surrounding elements act as if it were in it's original position in the normal flow... but it's not. This is why a relative element can overlap it's parent (like in Rel 1).
当脱离正常的文档流时,周围的元素就好像它在正常流中的原始位置一样......但事实并非如此。这就是为什么一个相对元素可以与它的父元素重叠(就像在 Rel 1 中一样)。
回答by SoEzPz
Did you try this?
你试过这个吗?
<div style="position: relative; right: -20%; bottom: -20%;">some text</div>
or rather
更确切地说
<div style="position: relative; right: -80%; bottom: -80%;">some text</div>