Why does setting the `right` CSS attribute push an element to the left?

三世轮回 提交于 2019-12-11 04:25:21

问题


I have a very basic page with two elements, an outer green box, and inner blue box. I am confused as to why setting the right attribute on the inner box would move it to the left? Furthermore I am confused as to why right:0 would not align the boxes right edge to the right edge of the parent box? Here is my short example page...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <style type="text/css">
            #outer {
                background-color : green;
                width : 500px;
                height : 500px;
            }

            #inner {
                position : relative;
                background-color : blue;
                height : 400px;
                width : 400px;
                top : 10px;
                right : 20px;
            }
        </style>
    </head>
    <body>
        <div id="outer">
            <div id="inner">


            </div>

        </div>
    </body>
</html>

回答1:


Setting the right property indicates how far from the right edge your element should be. Think of it as setting a new point of origin. By default, your origination is the top-left of the containing element. You can use bottom and right to change this.

When your element is positioned relative, its right-origin will be the natural location of its right-edge. This is why your element is shifted to the left 20px. If you changed the position value to absolute, the new point of origin will be the right edge of the nearest positioned container, or the viewport itself. In your case, it's the viewport.

For more, see http://www.w3.org/wiki/CSS/Properties/right




回答2:


Furthermore I am confused as to why right:0 would not align the boxes right edge to the right edge of the parent box?

You need to set the parent box to position:relative (or absolute, or fixed) if you want it to establish a new coordinate system for all descendants. Otherwise the inner box is still being positioned relative to the body.

For example, compare these two demos:
position:relative outer
position:static outer




回答3:


Throw in a

float:right;

to your inner div and all will work as you expect it.




回答4:


Setting right is how much you want to push it from the right



来源:https://stackoverflow.com/questions/10082567/why-does-setting-the-right-css-attribute-push-an-element-to-the-left

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!