Remove ':hover' CSS behavior from element

I have CSS that changes formatting when you hover over an element.

HTML:

<div class="test"> blah </div>

CSS:

.test:hover {  border: 1px solid red; }

In some cases I don't want to apply CSS on hover. One way would be to just remove CSS class from the div using jQuery but that would break other things since I also using that class to format its child elements.

So that led me to question: Is there a way to remove 'hover' css styling from an element?


I would use two classes. Keep your test class and add a second class called testhover which you only add to those you want to hover - alongside the test class. This isn't directly what you asked but without more context it feels like the best solution and is possibly the cleanest and simplest way of doing it.

Example:

HTML:

<div class="test"> blah </div>
<div class="test"> blah </div>
<div class="test testhover"> blah </div>

CSS:

.test {  border: 0px; }
.testhover:hover {  border: 1px solid red; }

Use the :not pseudo-class to exclude the classes you don't want the hover to apply to:

FIDDLE

<div class="test"> blah </div>
<div class="test"> blah </div>
<div class="test nohover"> blah </div>

.test:not(.nohover):hover {  
    border: 1px solid red; 
}

This does what you want in one css rule!


One method to do this is to add:

pointer-events:none;

to the element you want to disable hover on.

(note: this also disables javascript events on that element too, click events will actually fall through to the element behind ).

Browser Support (95.13% as of March 21,2018)

This seems to be much cleaner

/**
* This allows you to disable hover events for any elements
*/
.disabled {
  pointer-events: none;  /**<-----------*/
  opacity: 0.2;
}

.button {
  border-radius: 30px;
  padding: 10px 15px;
  border: 2px solid #000;
  color: #FFF;
  background: #2D2D2D;
  text-shadow: 1px 1px 0px #000;
  cursor: pointer;
  display: inline-block;
  margin: 10px;
}

.button-red:hover {
  background: red;
}

.button-green:hover {
  background:green;  
}
<div class="button button-red">Im a red button hover over me</div>

<br/>

<div class="button button-green">Im a green button hover over me</div>

<br/>

<div class="button button-red disabled">Im a disabled red button</div>

<br/>

<div class="button button-green disabled">Im a disabled green button</div>
链接地址: http://www.djcxy.com/p/88030.html

上一篇: 在响应式设计上更改Div订单

下一篇: 从元素中删除':hover'CSS行为