简体   繁体   中英

Expand hover area while keeping background color

I have a div that I want to expand the "hover area" of. (If your mouse is just outside of the element, the css :hover selector should still be in effect.)

I tried creating a transparent border: ( border:10px solid transparent; ) Unfortunately, my div has a background color, and the background "leaked" into the border area. (See fiddle for demonstration of the issue.)

I also tried using outline instead of border, but the outline doesn't seem to "count" as a part of the element when it comes to hovering. (It looks right, but won't detect the extra hover area.)

Is there any way to do this with plain CSS (preferably not many extra elements)? If not, is there a simple method using vanilla JS ( no jQuery )?

 $("#toggle").click(function(){ $("#attempt").toggleClass("border"); }); 
 #attempt { width:100px; height:200px; background:#aaa; margin:50px; } #attempt.border { margin:20px; /* Change margin to keep box in same place after border adds size */ border:30px solid transparent; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <div id="attempt"></div> <button id="toggle">Toggle Border</button> <p>Border (in the ideal case) would not change the element's background. However, adding the 30px border (even when transparent), will cause the background to change size.</p> 

All you need to prevent the background to leak is the box-sizing property. It's a very important one. Just add it to #attempt :

#attempt {
  box-sizing: border-box;
}

Check out the updated fiddle here . You can learn more about box-sizing here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM