What does “top: 0; left: 0; bottom: 0; right: 0;” mean?

☆樱花仙子☆ 提交于 2019-11-27 11:36:36

What happens when you use left and right (or top and bottom) at the same time is confusing because the spec [6.3. Absolute positioning] tells us that:

For absolutely positioned elements whose containing block is based on a block-level element, this property is an offset from the padding edge of that element.

So how can setting position affect the size of an element? The reason stems from how widths are calculated, which is buried in another section of the spec, [8.1. The width of absolute or fixed positioned, non-replaced elements].

If you specify both left and right and your element's width is not auto, then what you are saying really doesn't make sense, and right is ignored (all statements apply equally well to top/bottom/height):

If none of left/right/width is auto...the values are over-constrained, ignore the value for left (in case the direction property of the containing block is rtl) or right (in case direction is ltr) and solve for that value.

But if your element has no width set, or width is (the default) auto, this rule kicks in:

If width is auto, left and right are not auto, then solve for width.

Finally, the equation given that determines the values for these elements is:

'left' + 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' + 'right' = width of containing block

We can clearly see that after plugging in our values for left and right and the others, width is the unsolved (and unconstrained) variable, which will turn out to be width of containing box - left - right (more or less) or to put another way: "fill in the space between the offsets".

You can make 100% width and 100% height using top: 0; left: 0; bottom: 0; right: 0;

Example: You have one div there is no fixed width & height for that div. in this case you can apply this style and make 100% width & height.

div{
 position: absolute;
 top: 0;
 right: 0;
 bottom: 0;
 left: 0;
}

JSFIDDLE DEMO

{

    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;

}

Essentially what these property does is it expands your div or any other element containing above property to one full screen. Although if your web page is larger than one full screen you can scroll downwards to see the remaining of your page i.e the styled element is still dependent on your lower page.

 {

            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;

}

Fixed position on the other hand does the same thing but with one more advantage of non scrolling . It means you can have one entire full screen over your page which can be triggered as and when required and your upper div containing the above property will be independent of lower page.

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