CSS relative + right (or bottom) almost NEVER work

2019-02-02 10:32发布

I've been writing CSS for quite some time now.

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.

3条回答
成全新的幸福
2楼-- · 2019-02-02 10:45

Relative positioning does work with bottom/right values, just not the way you were expecting:

http://cssdesk.com/RX24j

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

查看更多
做个烂人
3楼-- · 2019-02-02 10:50

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> 
查看更多
家丑人穷心不美
4楼-- · 2019-02-02 11:01

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.
查看更多
登录 后发表回答