html - 嵌套的父子悬停问题

标签 html css css-selectors

我有多个嵌套的父子元素。现在我正在寻找可能的解决方案,在任何 parent 悬停时我想更改仅在 parent 旁边的 child 的颜色。

<div class="parent">The Parent paragraph.
    <div  class="child">This is Child Para
        <div class="parent">The Parent paragraph.
            <div  class="child">This is Child Para
                <div class="parent">The parent paragraph.
                    <div  class="child">This is Child Para
                    </div>
                </div>
            </div>
        </div>
    </div>
</div> 

现在正如我在代码中所说,存在嵌套的 parentchild 关系。现在,如果您将鼠标悬停在第一个 parent 上,它应该只影响其关联的 child 类,而不是所有子类。

CSS 是:

div.parent:hover > .child:first-of-type {
    background: red;
}

我什至尝试过 first-of-type 但它不起作用。

要实现这一目标,需要对 css 进行哪些更改?

Fiddle

最佳答案

您不能使用您当前的 CSS 代码执行此操作,如下所示:

div.parent:hover > .child:first-of-type {
    background: red;
}

正在选择所有这些:

<div  class="child">This is Child Para
    <div class="parent">The Parent paragraph.
        <div  class="child">This is Child Para
            <div class="parent">The parent paragraph.
                <div  class="child">This is Child Para
                </div>
            </div>
        </div>
    </div>
</div>

因为所有内容都在 .child div 中。另一方面,您可以将要变为红色的文本包装在 <p> 中。或 <span>然后用 css 选择它,就像这样。

p:hover + div > p {
    background: red;
}
<div class="parent">
  <p>The Parent paragraph.</p>
  <div  class="child">
    <p>This is Child Para</p>
    <div class="parent">
      <p>The Parent paragraph.</p>
      <div  class="child">
        <p>This is Child Para</p>
        <div class="parent">
          <p>The Parent paragraph.</p>
          <div  class="child">
            <p>This is Child Para</p>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div>This is second Para</div>
</div>

CodePen

关于html - 嵌套的父子悬停问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44195638/

相关文章:

html - 创建简单的按钮以使用 Bootstrap 中的列大小

css - 浏览器如何渲染伪元素选择器?

html - CSS 变换 - 旋转和倾斜不能一起工作

javascript - Ajax 只播放音频文件一次

html - 标题随着我增加字体大小而不断降低?

CSS 网格,绝对定位 css 网格元素中的元素 : IMPOSSIBLE

javascript - 单击按钮时复制 div

html - Bootstrap-rails,如何改变车身尺寸?

html - 用于触发 Google 跟踪代码管理器的 CSS 选择器

html - 如何使用 nth-child() 选择一个 div?