Stylize elements at various levels above

Asked

Viewed 93 times

3

I would like to know how to change the background of div#whatever by clicking on a li, as in the example below. (using css only)

<div class="whatever"></div>
 <section class="content">
        <article class="personagens">
            <h2>Lista de Pokémons</h2>
            <h2>Lista de Digimons</h2>
            <ul>
                <li>Bulbasaur</li>
                <li>Ivysaur</li>
            </ul>

2 answers

3

To do this only with HTML/CSS it is necessary to use a hack with checkbox.

Mind the adaptation I made to your code in that fiddle:

#btnControl {
  display: none;
}
#btnControl:checked + .whatever {
  background: red;
}
.whatever {
  width: 50px;
  height: 50px;
  background: gray;
}
<input type="checkbox" id="btnControl" />
<div class="whatever"></div>

<section class="content">
  <article class="personagens">
    <h2>Lista de Pokémons</h2>
    <h2>Lista de Digimons</h2>
    <ul>
      <li>
        <label class="btn" for="btnControl">Bulbasaur</label>
      </li>
      <li>
        <label class="btn" for="btnControl">Ivysaur</label>
      </li>
    </ul>
  </article>
</section>

Source

3

if you want to do purely with css gets like this

#a:hover + #b {
    background: #ccc;
}
<div id="a">Div A</div>
<div id="b">Div B</div>

This is just an ex but you adapt to your li

  • Thanks for your help, Jasar, but I’ve tried this. What I need to do is change the div.whatever from a click on a li contained within other elements, as in the above structure.

  • Pablo. Use the :active selector which will simulate the click.

  • 1

    The way our friend Felipe Correia posted works is an application of what I’ve been through. tbm can be done with a href because <a> has the active property after clicking,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.