关于CSS:absolute定位

前言

虽然会脱离文档流,但是不能排斥absolute定位,且其实在太强大

正文

先引用w3c对于 containing-block的说明

The position and size of an element’s box(es) are sometimes computed relative to a certain rectangle, called the containing block of the element. The containing block of a static or relative element is defined in the Box Model [CSS3BOX]. The containing block of a sticky element is the same as for a relative element. For fixed and absolute, it is defined as follows:

  1. If the element has position: fixed, the containing block is established by the viewport in the case of continuous media or the page area in the case of paged media.
  2. If the element has position: absolute, the containing block is established by the nearest ancestor with a position other than static, in the following way
  1. In the case that the ancestor is block-level, the containing block is formed by the padding edge of the ancestor.
  2. In the case that the ancestor is inline-level, the containing block depends on the direction
    1. If the direction is ltr, the top and left of the containing block are the top and left content edges of the first box generated by the ancestor, and the bottom and right are the bottom and right content edges of the last box of the ancestor.
    2. If the direction is rtl, the top and right are the top and right edges of the first box generated by the ancestor, and the bottom and left are the bottom and left content edges of the last box of the ancestor.

即:当当前元素定位为absolute时,标准会赋予改元素一个 containing-block而该block的宽度和高度是由top、left、right、bottom来决定的

而absolute定位时,如果该元素显式设置了width和left和right则只会应用left和width,right会被忽略,同理应用于top、bottom、height

但是上述情况的一些应用会令人产生些思考:
如下代码:



  

结果是:


关于CSS:absolute定位_第1张图片
结果

观察结果:

  • 没有为children设置height属性情况下获取到了高度
  • 在parent左边开始往右80px的区域内做到了水平居中(margin:auto)
    说明什么呢:
    看下parent图:


    关于CSS:absolute定位_第2张图片
    parent

其实根据开头的引用,绿色区域其实就是containing-block的大小,而我们设置了width则width小于了containing-block宽度,取自身宽度,然后再margin:auto自然就居中了。

说白了就是:containing-block 相当于在元素外围套了层div,且元素的左上角顶住containing-block的左上角。

说多了很难理解,自己多改改代码自然就有深刻体会了。

比如自行运行下面代码:



  
关于CSS:absolute定位_第3张图片
结果

结尾

至此前置知识准备完毕,这篇是自己查了stackoverflow和w3c标准得出的结论,对错与否不做保证,目前为止还与自己的认知没有出入。

你可能感兴趣的:(关于CSS:absolute定位)