Search code examples
htmlcsscss-transitionssiblingstranslate-animation

CSS translate button on sibling hover


I'm trying to create a stack of buttons that will slide out from underneath the top hovered button, but it's not working in my Codepen (http://codepen.io/dmoz/pen/xIsfL).

Here's the code:

HTML

<button class="one"></button>
<button class="two"></button>
<button class="three"></button>
<button class="four"></button>
<button class="five">^</button>

CSS

button {
  margin: 0;
  font-size: 12px;
  padding: 0;
  border: 0 none;
  cursor: pointer;
  color: #fff;
  width: 60px;
  height: 60px;
  display: block;
  text-transform: none;
  border-radius: 0;
  background-color: #0078E7;
  background-image: none;
  box-shadow: none;
  position: absolute;
  overflow: visible;
}
.one {
  background-color: #3b5997;
  color: #ffffff;
  left: 10;
  -webkit-transition: 0.2s ease-out;
  -moz-transition: 0.2s ease-out;
  -o-transition: 0.2s ease-out;
  transition: 0.2s ease-out;
}
.two {
  background-color: #ba0f16;
  color: #ffffff;
  left: 10;
  -webkit-transition: 0.2s ease-out;
  -moz-transition: 0.2s ease-out;
  -o-transition: 0.2s ease-out;
  transition: 0.2s ease-out;
}
.three {
  background-color: #d64937;
  color: #ffffff;
  left: 10;
  -webkit-transition: 0.2s ease-out;
  -moz-transition: 0.2s ease-out;
  -o-transition: 0.2s ease-out;
  transition: 0.2s ease-out;
}
.four {
  background-color: #0073b2;
  color: #ffffff;
  left: 10;
  -webkit-transition: 0.2s ease-out;
  -moz-transition: 0.2s ease-out;
  -o-transition: 0.2s ease-out;
  transition: 0.2s ease-out;
}
.five {
  background-color: #ffffff;
  border: 1px solid #888888;
  color: #888888;
  left: 10;
}
.five:hover ~ .one {
  left: 70px;
}
.five:hover ~ .two {
  left: 130px;
}
.five:hover ~ .three {
  left: 190px;
}
.five:hover ~ .four {
  left: 250px;
}

Anyone see why it's not working?


Solution

  • The CSS3 selector ~ only works for siblings that come AFTER the first element, regardless of how many siblings are between. The CSS2.1 selector + works only on the immediate NEXT element. Thus your code won't work since .five is the last element. There is no selector for previous siblings.

    If you move the fifth button before the others and add z-index to it, it will work, see http://codepen.io/anon/pen/kEjwe

    UPDATE: As requested, the CodePen example now has a wrapper div rendering the buttons child elements. Thus, the siblings selector is no longer required. This way, the individual buttons can be clicked when the wrapper is hovered.