19

我写 CSS 已经有一段时间了。

我注意到了

<div style="position: relative; right: 20%; bottom: 20%;">some text</div> 

从不工作!

相对定位适用于指定的左和上,但不适用于右/下。为什么?

解决此问题的快速解决方法是改用“绝对”并以像素为单位指定右/下,但我需要一个理由。

另外,如果我错了,请纠正我。不管外部容器是绝对定位还是相对定位,将某些东西“相对”于该容器的边界定位是否没有多大意义,或者容器内的元素是否应该始终“绝对”定位?

谢谢你。

4

5 回答 5

18

绝对与相对 - 解释 CSS 定位

相对定位使用与绝对定位相同的四个定位属性。但不是根据浏览器视口确定元素的位置,而是从元素仍处于正常流程中的位置开始。
于 2013-04-30T02:03:51.907 回答
8

相对定位确实适用于底部/右侧值,而不是您期望的方式:

http://cssdesk.com/RX24j

将相对元素上的位置值视为边距,周围元素会简单地忽略。“边距”将始终相对于它在正常文档流中的先前位置移动元素,但同时将其从正常流中删除。

当超出正常文档流时,周围元素的行为就好像它处于正常流中的原始位置......但事实并非如此。这就是为什么一个相对元素可以与它的父元素重叠(就像在 Rel 1 中一样)。

于 2013-04-30T02:34:38.250 回答
2

你试过这个吗?

<div style="position: relative; right: -20%; bottom: -20%;">some text</div> 

更确切地说

<div style="position: relative; right: -80%; bottom: -80%;">some text</div> 
于 2015-06-02T23:12:59.423 回答
1

不建议 :

left : 0%   //will set it to left 
left : 100% //will set it to right => you need to get the width of the element and subtract it using calc ( 100% - width)
于 2020-06-12T14:12:33.120 回答
0

从父元素中删除位置左、右、上、下,并根据需要将其放入子元素中

.parent_class
{
    background: #ff0000 ;
    position: absolute;
    transition: 0.8s ease-out;
    left:0;   //" remove this from here"
    top:0;   // " remove this from here"
    z-index: -1;
}

.child_class
{   
    width: 0px;
    height: 70px;
    right: 0; //"now it will work"
    bottom: 0;//"now it will work"
}
于 2020-07-02T13:20:38.703 回答