Joshua Sortino
Joshua Sortino

Reputation: 2417

Using the :target selector to affect an unrelated DIV (without Javascript)?

Is it possible to use the :target CSS selector to affect another DIV? For example, when a user visits http://website.com/#button could you style the .photo element if the elements were structured as below?

<div class="gallery">
  <ul>
   <li class="photo">
   <li class="photo">
  </ul>
<div>
<div id="button">Button Text</div>

Upvotes: 0

Views: 2037

Answers (2)

robertc
robertc

Reputation: 75717

You can affect multiple elements, but they'll all have to be related to the element that's the target. The easiest way to do this is to put the id on a wrapper element:

<div id="gallery1">
    <div class="gallery">
      <ul>
          <li class="photo">Photo</li>
          <li class="photo">Photo</li>
      </ul>
    </div>
</div>
<div id="gallery2">
    <div class="gallery">
      <ul>
          <li class="photo">Photo</li>
          <li class="photo">Photo</li>
      </ul>
    </div>
</div>
<a href="#gallery1">Gallery 1</a>|<a href="#gallery2">Gallery 2</a>

Then you can have rules like this:

.gallery {
    //rules for when gallery is not the target
}
:target .gallery {
    //rules for when the gallery is the target
}

Here's an example.

Upvotes: 1

Tetaxa
Tetaxa

Reputation: 4403

:target checks the hash part of the url and looks for matching a id on an element. So yes, you can affect another element, but it needs an id that matches the current hash part. Here's an example http://jsfiddle.net/Tetaxa/egF3d/

Upvotes: 3

Related Questions