codebreaker
codebreaker

Reputation: 813

Negative margins and borders

I have some images I want to stack using negative margins. However, since stacking images without clearly defined boundaries can be visually confusing, I figured I should add a border around them. Strangely, the even though the images stack correctly, their borders end up underneath the previous element.

Why is this the behavior I'm getting, and is there a way to make the borders appear at their intuitive level?

#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: On Firefox, this is what it looks like: firefox-borders

Upvotes: 6

Views: 6268

Answers (2)

G-Cyrillus
G-Cyrillus

Reputation: 105853

You may use transform to force drawing of borders too in FF:

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>

Upvotes: 3

j08691
j08691

Reputation: 207861

The issue doesn't appear in Chrome but does in Firefox and IE. The easy solution appears to just do something like set the position of the images to relative:

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

Upvotes: 4

Related Questions