css - 为什么绝对定位元素不忽略它的兄弟位置,出现在它之后?

标签 css css-position

<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>

预期行为的图片:

enter image description here

很可能我不明白position:relativeposition:absolute在这种情况下一起工作。谁能解释为什么没有发生图片上所示的行为?

最佳答案

这是由于<a>的显示方式所致用 CSS 表示。通常,它是 display: inline .绝对定位works quite differentlyposition: relative ancestor 是一个内联元素:

The containing block of an element is defined as follows:

  1. 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.

<a> 生成的行内框(包含 <img> )与其所在的行框高度相同,并且 <img> 的高度,它本身是内联的,是无关紧要的。因此,absposed 元素被放置在与行框 <img> 大致相同的高度。坐在。 <img>之所以这样定位是因为它位于 <a>基线 .

如您所想,设置 <a>display: block产生预期的行为。

关于css - 为什么绝对定位元素不忽略它的兄弟位置,出现在它之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37032227/

相关文章:

html - 绝对位置的文本换行遵循父级的边缘

css - 使用 transform on scroll 将元素位置固定到父级

javascript - 动态更改 iframe 标记源的脚本

javascript - Foundation zurb 导航栏

css - 是否有任何替代方法可以将图像定位在不同分辨率的特定位置的页面中

html - 位置 :fixed not working on chrome but works in firefox

jquery - 包含位置 : absolute elements inside of a div, 以便可以在其前后插入position:relative div

javascript - 如何使用 Jquery 将 txt 文件加载到 div 选项卡中

javascript - A4 大小的 html 内容溢出

html - 继续扩展内容而不是将页脚向下推