CSS change style of different element upon active

Travis Liew picture Travis Liew · Mar 24, 2014 · Viewed 9.9k times · Source

Trying to change the content of an image by clicking another image (image gallery viewer), using pure HTML/CSS.

I am using the gumby.css framework and currently have the following HTML:

<section id="sect">
    <div class="three columns">
        <img src"/images/help.png">
    </div>
    <div class="one column">
        <img src"/images/help.png">
    </div>
</section>

And the following css:

#sect .three.columns img:hover {
    content:url("/images/about.png");
    border: 5px solid red;
}

#sect .one.column img:active ~ #sect .three.columns img {
    content:url("/images/about.png");
    border: 5px solid red;
}

The first css rule for #sect .three.columns img:hover works perfectly, indicating I have selected the right element. But the second one #sect .one.column img:active ~ #sect .three.columns img does nothing upon active.

Refer to here for the meaning of ~.

Anyone have any ideas?

Thanks.

Answer

SW4 picture SW4 · Mar 24, 2014

As noted in the comments, this isnt possible in the way you are currently implementing.

CSS rules depend on degrees of decendancy and cannot traverse the DOM, by say, ascending up one parent level, then moving across and back down (in layman terms). They are limited to only identifying siblings and children.

The content style is also only available to :before and :after pseudo elements.

As such, the alternative would be to apply the operation to the active state of the parent elements, removing the child images, and referencing the background-image and not content property e.g.:

Demo Fiddle

HTML

<section id="sect">
    <div class="three columns"></div>
    <div class="one column"></div>
</section>

CSS

.column, .columns {
    height:200px;
    width:200px;
    background-image:url(http://phaseoneimageprofessor.files.wordpress.com/2013/07/iqpw29_main_image_.jpg);
    background-size:cover;
}
.three.columns:hover ~ .one.column {
    border:1px solid red;
    background-image:url(http://upload.wikimedia.org/wikipedia/commons/9/9c/Image-Porkeri_001.jpg);
}