负边距和边框

5
我有一些图片,想要使用负边距进行堆叠。然而,由于没有明确定义的边界会使图像堆叠时视觉上混乱,所以我决定在它们周围添加边框。奇怪的是,即使这些图像正确地堆叠,它们的边框也会出现在前一个元素下面。
为什么会出现这种行为,是否有办法使边框出现在它们直观的位置上?

#second {
  margin-top: -50px;
  margin-left: 20px;
}

img {
  border: 5px ridge green;
  display: block;
}
<div><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/RCA_Indian_Head_test_pattern.JPG/312px-RCA_Indian_Head_test_pattern.JPG" height="100" width="auto"><img id="second" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/RCA_Indian_Head_test_pattern.JPG/312px-RCA_Indian_Head_test_pattern.JPG" height="100" width="auto"></div>

EDIT: 在Firefox上,看起来是这样的:firefox-borders

在Chrome上,第二张图片的边框与第一张重叠。你用的是什么浏览器?编辑:在Internet Explorer 11上不起作用。 - Alexandre
1
在Chrome上看起来很好,但Firefox显示有问题。 - j08691
是的,它是Firefox。 - codebreaker
在Firefox中发布问题的图片。 - Wes Foster
2个回答

3
问题在Chrome中不存在,但在Firefox和IE中存在。简单的解决方案似乎就是将图像的位置设置为相对定位:

#second {
  margin-top: -50px;
  margin-left: 20px;
}

img {
  border: 5px ridge green;
  display: block;
  position: relative;
}
<div><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/RCA_Indian_Head_test_pattern.JPG/312px-RCA_Indian_Head_test_pattern.JPG" height="100" width="auto"><img id="second" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/RCA_Indian_Head_test_pattern.JPG/312px-RCA_Indian_Head_test_pattern.JPG" height="100" width="auto"></div>


同时为了确保重叠,可能建议使用 z-index - DaniP
1
@DaniP - 对于某些情况可能需要,但在这里似乎并不必要。 - j08691
同意,只是想指出这是一个选项,如果涉及到更多的图像。 - DaniP

3

你可以在 Firefox 中使用 transform 强制绘制边框:

ff screenshot

#second {
  margin-top: -50px;
  margin-left: 20px;
}

img {
  border: 5px ridge green;
  display: block;
  }

/* FF debug*/
div + div img {
  transform:scale(1);/* transform + anyvalue that does nothing new forces the layout to be redrawn */
}
div {float:left;
  margin:1em;
<div><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/RCA_Indian_Head_test_pattern.JPG/312px-RCA_Indian_Head_test_pattern.JPG" height="100" width="auto"><img id="second" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/RCA_Indian_Head_test_pattern.JPG/312px-RCA_Indian_Head_test_pattern.JPG" height="100" width="auto"></div>
<div><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/RCA_Indian_Head_test_pattern.JPG/312px-RCA_Indian_Head_test_pattern.JPG" height="100" width="auto"><img id="second" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/RCA_Indian_Head_test_pattern.JPG/312px-RCA_Indian_Head_test_pattern.JPG" height="100" width="auto"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接