0

I have 3 divs arranged vertically with 1px, overlapping borders. When I hover over the bottom div, its whole border is highlighted. However, when I hover over the top or middle divs, the bottom portion of the border is obscured by the div below. How can I fix this? I tried setting z-index on the hover style, but it doesn't appear to force the div above the other siblings.

.box {
  border: 1px solid #ccc;
  padding: 0.25em;
  width: 100px;
}
.box:nth-child(2) {
  margin-top: -1px;
}
.box:nth-child(3) {
  margin-top: -2px;
}
.box:hover {
  border-color: #000;
  z-index: 1 !important;
}
<div class="box">Top</div>
<div class="box">Middle</div>
<div class="box">Bottom</div>
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
  • Why are you overlapping the borders if you don't want them to overlap? I presume the very reason for your overlap is to hide the extra pixel between elements... so that's precisely what you get. – leigero Mar 30 '15 at 16:57
  • 1
    Related: http://stackoverflow.com/questions/20208200/css-shadow-overlapping-issue, http://stackoverflow.com/questions/27161796/overlap-the-image-on-hover – Josh Crozier Mar 30 '15 at 17:02
  • also your `margin-top: -1px;` should just go in the `.box` properties, there is no need for listing all the children differently here. – leigero Mar 30 '15 at 17:04
  • @leigero I used the different *margin-top*s because I was having trouble getting the borders to overlap. Using `position: relative` seems to fix that as well. – Uyghur Lives Matter Mar 30 '15 at 17:07
  • I would do it without the nth-child http://jsfiddle.net/ookb997e/ – Stickers Mar 30 '15 at 17:19

2 Answers2

5

You need to add position: relative; in order for z-index to work as it applies only to positioned elements.

http://philipwalton.com/articles/what-no-one-told-you-about-z-index/

Kaloyan
  • 7,262
  • 4
  • 32
  • 47
3

Very simple, just add position:relative; to .box (you already have the z-index on hover) to establish the stacking context required for it to work the way you need it.

.box {
    position: relative;
    /* rest of the styles */
}

Demo http://jsfiddle.net/L6sysroh/

Read more on stacking context.

Arbel
  • 30,599
  • 2
  • 28
  • 29