<a>
位于相对,而<span>
嵌套在其中并绝对定位。然而,<span>
出现在图像的下 左 Angular 下方,而不是出现在其相对父级的上 左 Angular 。我无法理解为什么不忽略它是 sibling 的立场。
这是我的代码:
.pos-rel {
position:relative;
}
.pos-abs {
position:absolute;
top:0px;
right:0px;
}
<a href="#" class="pos-rel">
<img src="http://placehold.it/270x270" class="img-responsive">
<span class="label label-primary pos-abs">Overlay</span>
</a>
预期行为的图片:
很可能我不明白position:relative
和 position:absolute
在这种情况下一起工作。谁能解释为什么没有发生图片上所示的行为?
最佳答案
这是由于<a>
的显示方式所致用 CSS 表示。通常,它是 display: inline
.绝对定位works quite differently当position: relative
ancestor 是一个内联元素:
The containing block of an element is defined as follows:
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:
- 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.
由 <a>
生成的行内框(包含 <img>
)与其所在的行框高度相同,并且 <img>
的高度,它本身是内联的,是无关紧要的。因此,absposed 元素被放置在与行框 <img>
大致相同的高度。坐在。 <img>
之所以这样定位是因为它位于 <a>
的基线 .
如您所想,设置 <a>
至 display: block
产生预期的行为。
关于css - 为什么绝对定位元素不忽略它的兄弟位置,出现在它之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37032227/