CSS children 之间的过渡

CSS Transition between children

快速提问。如果我将鼠标悬停在 child 上以瞄准另一个 child,或者一个单独的 div 与另一个单独的 div 是否有效?

只有将 children 放入容器中并将鼠标悬停在 parent 上,我才能过渡到工作状态。这是什么规则?

示例 1(不起作用):

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
}

.underline {
  width: 0px;
  height: 2px;
  background-color: black;
  transition: 0.4s;
}

h2:hover .underline {
  width: 165px;
}
<body>

    <h2>Hover Over Me</h2>
    <div class="underline"></div>

</body>

示例 2(不起作用)

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 180px;
  height: 50px;
}

.underline {
  width: 0px;
  height: 2px;
  background-color: black;
  transition: 0.4s;
}

h2:hover .underline {
  width: 165px;
}
<body>

  <div class="container">
    <h2>Hover Over Me</h2>
    <div class="underline"></div>
  </div>

</body>

示例 3(有效)

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 180px;
  height: 50px;
}

.underline {
  width: 0px;
  height: 2px;
  background-color: black;
  transition: 0.4s;
}

.container:hover .underline {
  width: 165px;
}
<body>

  <div class="container">
    <h2>Hover Over Me</h2>
    <div class="underline"></div>
  </div>

</body>

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 180px;
  height: 50px;
}

.underline {
  width: 0px;
  height: 2px;
  background-color: black;
  transition:0.4s;
}

h2:hover + .underline {
  width: 165px;
}
<body>

  <div class="container">
    <h2>Hover Over Me</h2>
    <div class="underline"></div>
  </div>

</body>

您可以检查 This 的 css 个选择器