HTML objects growing and pushing others

How could I make it so that given two elements let’s say these boxes: enter image description here

If I clicked over one, it would grow, and the other would shrink like and vice versa: enter image description here

How can I do this?

I have seen this sort of done with CSS, using the focus tag and adjusting the width. But I have two problems there, first how could I affect the other element, and second as far as I can tell adjusting width will only stretch them right. I have seen people change the way they float the elements to deal with that, but I don’t want to move them around the page to do this.


solution

Here are 2 examples without Javascript/jQuery:

Pure CSS - Trigger on click: (example)

Using the checkbox hack in CSS you can effectively toggle the widths of the elements when the checkbox is :checked. Here is what part of the CSS looks like:

input[type=checkbox]:checked ~ .red {
  width:70%;
}
input[type=checkbox]:checked ~ .green {
  width:20%;
}

Go to the example for the full CSS.

HTML

<input type="checkbox" id="toggle" />
<div class="red">
  <label for="toggle"></label>
</div>
<div class="green">
  <label for="toggle"></label>
</div>

You might also be interested in the original example I made. It takes a different approach, though it doesn’t fully work.

Pure CSS - Trigger on hover: (example)

Unfortunately, neither the adjacent selector, nor the general sibling selector can select previous elements, therefore it makes this a little difficult. I placed 2 general elements before the main elements in order to somewhat solve this issue.

.greenS:hover, .greenS:hover ~ .green,
.redS:hover, .redS:hover ~ .red {
  width:72%;
}
.greenS:hover ~ .redS, .greenS:hover ~ .red,
.redS:hover ~ .greenS, .redS:hover ~ .green {
  width:22%;
}

HTML

<div class="redS"></div>
<div class="greenS"></div>
<div class="red"></div>
<div class="green"></div>

Since this was tagged as JS/jQuery, here are 2 alternative solutions.

JS/jQuery - Trigger on click: (example)

$('.red, .green').click(function(){
  $('.red').toggleClass('expanded').next('.green').toggleClass('contracted');
});

JS/jQuery - Trigger on hover: (example)

$('.red').hover(function(){
$(this).toggleClass('expanded')
  .next('.green').toggleClass('contracted');
});
$('.green').hover(function(){
  $(this).toggleClass('expanded').prev('.red').toggleClass('contracted');
});