Search code examples
htmlcsscss-transforms

CSS transform without affecting child elements?


I am trying to have a card element move up on hover and then back down when it is no longer hovered. I am currently achieving this by using transform and translate in CSS. However, I have noticed that this can affect the children elements as well as the element that I want this animation affected by. Here is the HTML and CSS for the card that I have at the moment:

.server :hover {
  -moz-transform: translate(0, -2px);
  -ms-transform: translate(0, -2px);
  -o-transform: translate(0, -2px);
  -webkit-transform: translate(0, -2px);
  transform: translate(0, -2px);
  transition-duration: 0.3s;
  transition-timing-function: ease-in-out;
}
<div class="server">
  <div class="card m-2 p-1 text-center">
    <p>Child element</p>
  </div>
</div>


Solution

  • You've used a compound selector when what you probably want is a chain selector. Just add the :hover pseudo selector, without a space, directly to the element you want to affect.

    .card {
      /* transitions are needed when hover state ends, so set up rules here */
      transform: translate(0, 0);
      transition-property: transform;
      transition-duration: 0.3s;
      transition-timing-function: ease-in-out;
    }
    .card:hover { /* note: no space */
      transform: translate(0, -2px);
    }
    <div class="server">
      <div class="card m-2 p-1 text-center">
        <p>Child element</p>
      </div>
    </div>