How do the CSS top bottom left and right attributes work?

后端 未结 3 1545
你的背包
你的背包 2021-01-25 04:20

I was wondering what the logic was behind the CSS attributes for top, left bottom and right.

for exa

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 04:57

    Well, you need to understand the concept of positioning for this. Let us try to understand this. Consider you have the following structure:

    HTML:

    CSS:

    #divContainer {
        height:300px;
        position:relative;
        width:300px;
        background-color:Red;
    }
    
    #divElement {
        height:150px;
        position:absolute;
        width:150px;
        background-color: Orange;
        right:0px;
    }
    

    See this here: http://jsfiddle.net/3mQk2/

    As you can see, the divElement sticks to the right end corner of the divContainer. This is because position:absolute takes the element out of the normal 'flow of the document'. This in itself does not move the element (remove the right:0; and see). When you provide the right:0 value it understands 'make the distance between the current element (divElement) and its container 0px on the inside right side of the container'.

    This also happens because the container has position:relative attached to it. If instead, the position property of the container was set to static (which is the default by the way) in this manner:

    #divContainer {
        height:300px;
        position:static;
        width:300px;
        background-color:Red;
    }
    

    Then divElement's container would have been the window element and not the divContainer(yes, this is a aha!moment to many). In that case, the divElement would have 'stuck' to the corner of its container (i.e. the window).

    You can see this here: http://jsfiddle.net/35qc2/

    Hope this helps.

    EDIT: i know what it does, i was more wondering why the syntax of right:0, i know that position:right; doesn't exist but it would make more sense syntactically than right:0px.

    This is the comment you have made above. Let us try to break this down and examine it.

    "I know that position:right; doesn't exist"

    Yes, you are right. position:right does not exist.

    But it would make more sense syntactically than right:0px.

    Nope. It wouldn't. For this, you have to understand the fundamental responsibility of the properties. i.e.:

    position property: HOW the element is to be positioned.

    top, right, bottom, left: WHERE the element is to be positioned.

    That is these properties (top, right, bottom, left) are dependent on the position property.

    That's why these properties have no effect when the position property is set to static. They only come into picture when the position is NOT static.

提交回复
热议问题