问题
Here's the FIDDLE for play around.
I have created <div class="foo">
and have a generated CSS content using .foo:after
.
I want to have that generated content clickable by setting a link.
If I wrap the .foo
with an anchor it creates a link around .foo
and .foo:after
.
However I want to make the area of .foo:after
clickable, but not the .foo
itself.
Is there a way that I can achieve this using pure CSS? Perhaps changing the markup?
HTML
<div class="container">
<a href="http://example.com">
<div class="foo"></div>
</a>
</div>
CSS
.foo{
width: 400px;
height: 150px;
background-color: #DFBDE0;
}
.foo:after{
content: "";
position: absolute;
background-color: #CB61CF;
width: 100px;
height: 100px;
right: 0;
}
Screeshot
回答1:
I confirm the fix suggested by matchboxhero, and I share the concern of Roberrrt.
Hence I suggest moving your special class to the itself, or better still apply it to the outer container.
In other words, you create the specific behaviour either on the element that itself gets the special class (foo), or child elements thereof. But not the parent, or preceding/following sibling, or whatever else...:
.foo.container{
width: 550px;
position: relative;
}
.foo a div {
width: 400px;
height: 150px;
background-color: #DFBDE0;
}
.foo a div:after{
content: "";
position: absolute;
background-color: #CB61CF;
width: 100px;
height: 100px;
right: 0;
}
.foo a {
pointer-events: none;
}
.foo a div:after{
pointer-events: all;
}
<div class="foo container">
<a href="http://example.com">
<div></div>
</a>
</div>
回答2:
This should work, it stops the link being clickable but then allows it on the pseudo element using the pointer-events attribute.
a {
pointer-events: none;
}
.foo:after{
pointer-events: all;
}
You should put a class on the link so that it doesn't affect all links.
回答3:
Is there a reason for the clickable item to be made as an ::after?
Because, if not, a work around would be to put your anchor after .foo instead. Keeping the 'position: absolute' gives it the same position as your ::after item since the anchor is still in the container div.
<div class="container">
<div class="foo"></div>
<a class="after" href="http://example.com">CLICK ME !</a>
</div>
an updated fiddle: http://jsfiddle.net/wagor93h/3/.
That way, the pointers event on the foo div can still happen. (if it's text, for say, not being able to select any of it wouldn't be optimal)
来源:https://stackoverflow.com/questions/25465397/how-to-make-the-area-of-css-pseudo-element-clickable