Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

css - prevent a pseudo element from triggering hover?

If I have markup:

<div class="a b"></div>

where the .a class has a hover class associated with it

and the .b class has a pseudo element associated with it... like so:

div
{
    width: 100px;
    height: 100px;
}
.a { background: red; display: inline-block; }
.a:hover { background: green; }

.b:after
{
    content: '';
    display: inline-block;
    width: 100px;
    height: 100px;
    margin-left: 100px;
    background: pink;
}

Is it possible with css to prevent a pseudo element from triggering the .a class hover?

FIDDLE

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following css does the trick for modern browsers (not IE10-):

.b:after {
  pointer-events: none;
}

pointer-events: none allows elements to not receive hover/click events.

See this fiddle.


Caution

pointer-events support for non-SVG elements is in a relative early state. developer.mozilla.org gives you the following warning:

The use of pointer-events in CSS for non-SVG elements is experimental. The feature used to be part of the CSS3 UI draft specification but, due to many open issues, has been postponed to CSS4.

Chrome's box model interpretation of display: inline-block causes a flicker in the above fiddle.
If you switch to display: block instead, you will get the proper interpretation of the box.
Firefox does not have this issue.
To ensure consistent box model interpretation, use the following:

.b:after {
  pointer-events: none;
  display: block;
}

View this fiddle in Chrome to see the flicker effect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...