html – 负边距删除静态兄弟的背景属性

我在底部使用负边距来拉动相邻元素以重叠当前元素.我打算让它重叠.但我希望整个div重叠在图像上方.但是,事实证明它也删除了拉动元素的背景.有人能解释一下吗?

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <style>
    .div1 {
      background-color: black;
    }

    img {
      margin-bottom:-20px;
    }
  
  </style>
  
  <div class="container">
    <div class="row">
      <div class="col-xs-4">
        <img src="http://placehold.it/200x300" alt="">
        <div class="div1">
          Here is example text
        </div> 
      </div>
    </div>
  </div>

</body>
</html>

http://jsbin.com/mejoci/edit?html,css,output

编辑:当元素定位(固定|相对|绝对)时,即使没有设置位置,也是静态位置,这是默认位置.

最佳答案 在示例代码中,两个元素共享相同的堆栈上下文.

在这种情况下,定义元素如何分层的规则在the spec中定义如下:(粗体是我的)

Within each stacking context, the following layers are painted in back-to-front order:

  1. the background and borders of the element forming the stacking context.
  2. the child stacking contexts with negative stack levels (most negative first).
  3. the in-flow, non-inline-level, non-positioned descendants.
  4. the non-positioned floats.
  5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  7. the child stacking contexts with positive stack levels (least positive first).

所以你可以看到 – 在相同的堆叠上下文中 – 内联级元素(#5)被绘制在非内联级元素(#3)之上

所以在你的情况下 – 因为< img>和< div>共享相同的堆叠上下文和< img> element是一个内联级元素 – 它被绘制在< div>之上. – 即使< div>稍后在文档树顺序中发生.

看看这个codepen demo,这进一步说明了这一点

额外阅读:

Elaborate description of Stacking Contexts

Stacking without z-index (MDN)

Z-Index And The CSS Stack: Which Element Displays First?

点赞