abagshaw abagshaw -4 years ago 107
CSS Question

Trigger CSS :hover only when hovering over border box

I am creating a rectangular outline with a

5px
thin border box around an empty
<div>
. When the user hovers over the border I want the border to change colour. That's all working fine, but I don't want the border to remain changed when the user's mouse is inside the
<div>
because it's no longer actually on the border.

See an example here:
https://jsfiddle.net/qbcc1trt/



.outer {
position: relative;
overflow: hidden;
display: inline-block;
}
.myborder {
content: '';
position: absolute;
bottom: 5%;
left: 20%;
width: 40%;
height: 50%;
box-shadow: inset 0px 0px 0px 5px rgba(0, 0, 0, 0.6);
}
.myborder:hover {
content: '';
position: absolute;
bottom: 5%;
left: 20%;
width: 40%;
height: 50%;
box-shadow: inset 0px 0px 0px 5px rgba(100, 200, 100, 0.6);
}

<div class="outer">
<img src="https://s-media-cache-ak0.pinimg.com/736x/ff/00/5e/ff005e0fa600c51c5e36f6059bbe6053.jpg">
<div class="myborder"></div>
</div>





Any way to accomplish this?

Answer Source

:hover events only work on the top most element (and the elements inside). So you can achieve this effect by making another div the same size as your myborder but subtracting the size of the border. Then place it directly above myborder.

This way, the hover event will trigger while over the border (box shadow in your case) but no the inside. See the demo below

.outer {
  position: relative;
  overflow: hidden;
  display: inline-block;
}
.myborder {
  position: absolute;
  bottom: 5%;
  left: 20%;
  width: 40%;
  height: 50%;
  box-shadow: inset 0px 0px 0px 5px rgba(0, 0, 0, 0.6);
}

.hover-cover {
  position: absolute;
  bottom: calc(5% + 5px);
  left: calc(20% + 5px);
  box-shadow: none;
  z-index: 1;
  width: calc( 40% - 10px);
  height: calc( 50% - 10px);
}
 

.myborder:hover {
  box-shadow: inset 0px 0px 0px 5px rgba(100, 200, 100, 0.6);
}
<div class="outer">
<img src="https://s-media-cache-ak0.pinimg.com/736x/ff/00/5e/ff005e0fa600c51c5e36f6059bbe6053.jpg">
  
  <div class="hover-cover"></div>
  <div class="myborder"></div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download