CSS悬停不适用于子节点

发布于 2025-01-07 09:31:57 字数 514 浏览 3 评论 0 原文

我的 html 设置与此类似,唯一的区别是我的 '.inner 包裹得更深(例如

aaa
)

<div class="main">
    <div class="inner">aaa</div>
    <div class="main anOtherClass">
        <div class="inner">aaa</div>
    </div>
</div>

我的 css 是:

.main:hover .inner {
    border: 1px solid #000;
}

问题是,如果我将鼠标悬停在第一个 .main 上,我的所有.inners得到边界。我的目标只是让第一个 .inner 获得边框。这甚至可以在CSS中做到吗?

My html setup is similar to this, the only difference is that my '.inner's are wrapped much deeper (eg. <div><span><div class="inner">aaa</div></div></span>)

<div class="main">
    <div class="inner">aaa</div>
    <div class="main anOtherClass">
        <div class="inner">aaa</div>
    </div>
</div>

my css is:

.main:hover .inner {
    border: 1px solid #000;
}

The problem is, that if I hover onto the first .main all of my .inners get the border. My goal is only to have the first .inner get the border. Is this even possible to do in css?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜吻♂芭芘 2025-01-14 09:31:57

使用子选择器

.main:hover > .inner {
    border: 1px solid #000;
}

> 将此选择器限制为 .inner 元素,这些元素是 .main直接子元素,

SitePoint 对其进行了很好的解释:http://reference.sitepoint.com/css/childselector

如果您确定您想要第一个(如果有两个或多个相邻的)也使用 :first-child

.main:hover > .inner:first-child {
    border: 1px solid #000;
}

Use the child selector:

.main:hover > .inner {
    border: 1px solid #000;
}

The > constrains this selector to .inner elements that are a direct child of .main,

SitePoint explains it well: http://reference.sitepoint.com/css/childselector

If you're certain you only want the first one (in case there are two or more adjacent ones) use :first-child as well:

.main:hover > .inner:first-child {
    border: 1px solid #000;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文