position定位,设置top为百分数,如何计算?

position定位分别设置为relative,absolute。top,left都设置为100%,理论上说100%应该根据包含快的宽度计算,但实际上的计算值却不同。

html
<div class="z1">
  <div class="z2"></div>
</div>
<div class="z3">
  <div class="z4"></div>
</div>

css
.z1{
      position: relative;
    width: 400px;
    height: 400px;
    padding: 5px 10px;
    color: #fff;
    text-align: right; 
      background: #000;
      border: 5px solid yellow;
  }
    .z2{
      position: relative;
      width: 200px;
      height: 100px;
      padding: 5px 10px;
      color: #fff;
      text-align: right;
    z-index: 2;
      top: 100%;
      left: 100%;
      background: #C00;
      border: 5px solid blue;
    }
    .z3{
      position: relative;
    width: 400px;
    height: 400px;
    padding: 5px 10px;
    color: #fff;
    text-align: right; 
      background: #000;
      border: 5px solid yellow;
  }
    .z4{
      position: absolute;
      width: 200px;
      height: 100px;
      padding: 5px 10px;
      color: #fff;
      text-align: right;
    z-index: 2;
      top: 100%;
      left: 100%;
      background: #C00;
      border: 5px solid blue;
    }

得到的结果

clipboard.png

z2:

clipboard.png

z4:

clipboard.png
且Z4 的top,left均设置为100%,计算值却不同,求解答!!!


更新:最后z4的显示的图有问题
更新浏览器版本后:

clipboard.png

阅读 22.1k
3 个回答

首先top(bottom)、 left(right)的百分比的相对值分别是相对于包含块的高度、宽度的。

然后看结果,对于position:relative的元素而言,百分比的计算是相对于其包含块的“内容”盒(框)的宽高的,所以对于第一个就很好理解,宽高都是400所以值也就是400了;对于第二张图,absolute的元素百分比的计算是相对于其包含块的padding边界所形成的盒(框)来计算的,所以结果呢就是top 410(400 + 5 + 5) left 420(400 + 10 + 10)的,楼主的关于z4的图的left的计算值还是有误的,估计是doctype之类的问题,或者没及时更新(猜测。。)

http://blog.aijc.net/css/2014...

首先 position 当然不是根据宽度计算的,是根据高度计算的。paddingmargin 才是根据包含块的宽度计算的 (http://www.w3.org/TR/css3-box... and http://www.w3.org/TR/CSS2/box... )。

定位是相对于哪里,百分比又是相对于什么计算,取决于包含块 (containing block):

For other elements, if the element's position is 'relative' or 'static', the containing block is formed by the content edge of the nearest block container ancestor box.

If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed', in the following way:

  1. In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element. In CSS 2.1, if the inline element is split across multiple lines, the containing block is undefined.

  2. Otherwise, the containing block is formed by the padding edge of the ancestor.

If there is no such ancestor, the containing block is the initial containing block.

http://www.w3.org/TR/CSS2/vis...

可见这里相对定位的时候,定位 topleft 的起点是 content box 的顶端和左侧,百分比相对的值也是 content box 的高度。然而绝对定位的时候,定位的起点和百分比都是相对 padding box 而言的。

relative 是相对原来位置的(包括 padding ), 100% 是 width; absolute 是相对最近的 带有定位的 父节点的左上角(不包括padding), 100% 是 width + padding

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题