Reputation: 1138
I have part of an HTML definition which looks like this.
<div id="photoindex" class="content">
<div class="photocategory">
<a href="/photo/clouds"><img src="img.jpg"></a>
<h1><a href="/photo/clouds">Clouds</a></h1>
</div>
</div>
The h1
should be invisible until the image is hovered over, at which point the h1
becomes visible, and the img
opacity is reduced. My current attempt has a slight flaw which cannot be ignored.
div#photoindex h1 {
visibility: hidden;
}
div#photoindex h1:hover {
visibility: visible;
}
div#photoindex img:hover {
opacity: 0.7;
}
div#photoindex a:hover + h1 {
visibility: visible;
}
div#photoindex h1:hover + a {
opacity: 0.7;
}
With this, I can mouse over the image and have the h1
appear, and the image opacity go down. However, if I move the mouse over the h1
, the image opacity returns to normal. I've tried using the :first-child
and :last-child
selectors, but that doesn't appear to work. I've had no luck trying to apply things to .photocategory
either.
div.photocategory:hover a {
opacity: 0.7;
}
div.photocategory:hover h1 {
visibility: visible;
}
This changes the opacity, but has no apparent effect on the visibility of the h1
. Can I do what I want without Javascript? Perhaps a different HTML structure would work better?
Upvotes: 2
Views: 71
Reputation: 1138
I found what might possibly be a better way of doing things. If div.photocategory:hover
is used, then hovering over that element produces the effect, even if the cursor is not over the image at the time. This is not a problem for places where the image takes up the whole photocategory
, but for those where it does not, the problem arises.
The main problem was caused by a mouseover on the h1
causing that element to be activated, where we actually want to ignore it. To solve this issue, you can use the pointer-events
property as below.
div#photoindex div.photocategory h1 {
position: absolute;
visibility: hidden;
margin: -40px 0 0 0;
pointer-events: none;
}
div#photoindex div.photocategory a:hover {
opacity: 0.7;
}
div#photoindex div.photocategory a:hover + h1 {
visibility: visible;
}
This CSS more accurately represents the problem, and the result can be seen at this fiddle. Setting pointer-events: none;
drops pointer events through to the element below the h1
, in this case the img
element, and we do not need more CSS to modify the h1
opacity.
This fiddle illustrates the issue with using photocategory:hover
. Mousing over the blank space to the right of the image causes the hover event to be activated.
Upvotes: 0
Reputation: 3435
I think applying the styles to .photocategory
will work, assuming your parent divs aren't collapsing.
div#photoindex div.photocategory:hover a {
opacity: 0.7;
}
div#photoindex div.photocategory:hover h1 a {
opacity: 1;
}
div#photoindex div.photocategory:hover h1 {
visibility: visible;
}
div#photoindex div.photocategory h1 {
visibility: hidden;
}
Upvotes: 1