嵌套div可以忽略父级的悬停

时间:2017-10-10 04:47:15

标签: html css

如果div嵌套在另一个内部,嵌套div可以忽略父级的悬停。这是一个例子



.Box {
  width: 50px;
  height: 50px;
  background: red;
}

.Circle {
  width: 20px;
  height: 20px;
  background: blue;
  border-radius: 20px;
}

.Box:hover {
  animation: expand .5s normal forwards;
}

@keyframes expand {
  0% {
    transform: scale(1);
  }
  100% {
    transform: scale(1.6);
  }
}

<div class="Box">
  <div class="Circle"></div>
</div>
&#13;
&#13;
&#13;

在这个例子中,有一种方法可以使Box扩展而不是Circle

2 个答案:

答案 0 :(得分:2)

从技术上讲,父hover事件未应用于子项。

但是在你的情况下,孩子仍然受到影响,因为你正在缩放父母。因此,父母内部的所有内容也都在缩放。

为了对抗嵌套div的缩放比例,您可以在父div悬停时应用反向缩放效果。

.Box{
   width: 50px;
   height: 50px;
   background: red;
}

.Circle{
   width: 20px;
   height: 20px;
   background: blue;
   border-radius: 20px;
}

.Box:hover{ 
    animation: expand .5s normal forwards;
}

.Box:hover .Circle {
    animation: contract .5s normal forwards;
}

@keyframes expand {
    0% {
        transform: scale(1);
    }

    100% {
        transform: scale(1.6);
    }
}

@keyframes contract {
    0% {
        transform: scale(1);
    }

    100% {
        transform: scale(0.625);  /* 1 / 1.6 */
    }
}
<div class="Box">
    <div class="Circle"></div>
</div>

答案 1 :(得分:2)

因为您正在扩展父级,所以其中的所有内容都会受到影响。另一种解决方案是让圆圈有一个不同的兄弟,并在其上应用动画。

<强> CSS

  .Box {
    width: 50px;
    height: 50px;
    background: red;
  }

  .Circle {
    width: 20px;
    height: 20px;
    background: blue;
    border-radius: 20px;
    position: absolute;
    top: 10px;
    left: 10px;
  }

  .Container {
    position: relative;
  }

  .Box:hover {
    animation: expand .5s normal forwards;
  }

  @keyframes expand {
    0% {
      transform: scale(1);
    }
    100% {
      transform: scale(1.6);
    }
  }

<强> HTML:

<div class="Container">
  <div class="Box">

  </div>
  <div class="Circle"></div>
</div>

演示:http://jsfiddle.net/lotusgodkk/GCu2D/2157/

此处,圆圈的位置使其位置不受框

的影响