UPDATED: Still With Some Really Unique Tweaking!
Surprisingly, this piece of code functions in FF, Chrome, IE9 and 10 to achieve the desired outcome (check out the example). Yes, it's a bit of a "hack" as noted by Pumbaa80. However, I enjoy creating working hacks for challenges that may initially seem impossible. Admittedly, due to its unconventional nature, it may not work in all scenarios (especially more complex real-world situations).
What was Accomplished with the Update
- I believe I managed to fix a small bug in FF and Chrome where it would occasionally still display when hovering not directly over the
<a>
element.
- I discovered a workaround to make IE cooperate by inserting the
body:before
pseudo-element at z-index: -1
between the #p1
(z-index: -2
) and the parent #out
div. For this to function properly, the :before
must have a set background-color
and then be given a opacity: 0
(without this, it seems like it doesn't even exist for blocking purposes). It is important to note that there are at least two side effects (perhaps more) from this blocking technique: (a) Links within the #p1
won't be clickable, and (b) as mentioned in a comment by the OP, text within #p1
won't be selectable.
Below is the revised code primarily for the #sec
hover effect. Additionally, I've included the combined code here for the original #p1
hover effect now triggered by #out:hover
. Nonetheless, the code has been adjusted so only the <a>
element inside #out
activates the #out:hover
:
body:before { /* used for blocking hover of #p1 triggering */
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: -1;
background-color: cyan;
opacity: 0;
}
#out {
height: 0; /* no inherent height; fixed the occasional FF/Chrome hover bug */
}
#out:hover #p1, /* revised #p1 hover code */
#out:hover + div p { /* hover of #out triggers for #sec */
background-color: red;
}
#out a {
float: left; /* ensures #out only triggers on anchor */
}
#p1 {
float: left; /* clears the anchor */
width: 100%; /* maintains the normal div width of 100% */
position: relative; /* necessary for z-index */
z-index: -2; /* enables #out to trigger exclusively on anchor rather than #p1 hover */
}
#sec {
clear: left; /* clears above floats to preserve layout */
}
The primary challenge with a pure CSS solution lies in elements that are "not in relationship." My aim with this endeavor (largely successful for major browsers...though uncertain about mobile browsers, etc.) is to leverage the parent element relationship in a manner that allows only the hover of the <a>
(within that initial parent element) to trigger the :hover
on the parent element itself, thereby enabling me to implement hover effects for all <p>
elements.