Dynodzzo
Dynodzzo

Reputation: 75

Select non-sibling elements using only CSS3

I have three blocs, each containing another bloc. What I want is to select all the inner blocs when clicking on one of them.

Here's a Codepen illustrating my situation : http://codepen.io/anon/pen/viGDx

HTML

<div class="bloc-container">
  <div class="bloc"></div>
</div>

<div class="bloc-container">
  <div class="bloc"></div>
</div>

<div class="bloc-container">
  <div class="bloc"></div>
</div>

CSS

div.bloc-container {
  background-color: #D5CEFA;
  width: 300px;
  height:250px;
  display: inline-block;
}

div.bloc {
  background-color: #CEFAD5;
  width: 150px;
  height: 125px;
  margin: auto;

  transition: transform 0.2s ease-in;
}

div.bloc:active {
  transform        : scale(0.6);
  -moz-transform   : scale(0.6);
    -o-transform     : scale(0.6);
    -webkit-transform: scale(0.6);
}

I did it using the following Javascript code (commented in the Codepen):

$(document).ready(function() {
  var blocs = $('.bloc');

  blocs.bind('mousedown', function() {
    blocs.css('transform', 'scale(0.6)');
  });

  blocs.bind('mouseup', function() {
    blocs.css('transform', 'scale(1)');
  });
});

But I'm wondering how to do it using only CSS.

Upvotes: 0

Views: 174

Answers (2)

Oriol
Oriol

Reputation: 288660

You can do that (more or less) using :active pseudo-class in a parent:

CSS:

#wrapper:active .bloc {
    /* Your code */
}

HTML:

<div id="wrapper">
    <div class="bloc-container">
      <div class="bloc"></div>
    </div>

    <div class="bloc-container">
      <div class="bloc"></div>
    </div>

    <div class="bloc-container">
      <div class="bloc"></div>
    </div>
</div>

DEMO

Note that with CSS you can't always achieve exactly the same behavior than with JS, because CSS has no events.

Upvotes: 0

Mark
Mark

Reputation: 70

What you're looking for (the ability to select a 'cousin') would require a parent selector that could enable you to travel up DOM before coming back down again. Unfortunately CSS only provides selectors for descendants and siblings (not parents), neither of which can facilitate the behaviour you want.

I believe JavaScript is therefore required in this particular case.

Upvotes: 3

Related Questions