有 CSS 父选择器吗?

发布于 2025-01-20 05:36:27 字数 278 浏览 0 评论 0原文

如何选择锚定元素的直接父元素的< li>元素?

例如,我的CSS将是这样的:

li < a.active {
    property: value;
}

JavaScript执行此操作,但我希望有某种解决方法存在于CSS 2级。

显然有一些方法可以使用 正在由CMS吐出,因此我无法将活动元素移至&lt; li&gt;元素...(除非我主题为菜单创建模块,否则我不想做) 。

How do I select the <li> element that is a direct parent of the anchor element?

As an example, my CSS would be something like this:

li < a.active {
    property: value;
}

Obviously there are ways of doing this with JavaScript, but I'm hoping that there is some sort of workaround that exists native to CSS Level 2.

The menu that I am trying to style is being spewed out by a CMS, so I can't move the active element to the <li> element... (unless I theme the menu creation module which I'd rather not do).

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

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

发布评论

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

评论(30

当梦初醒 2025-01-27 05:36:27

W3C 的选择器级别 4 工作草案包括 a :has()提供此功能的伪类,除其他外:

li:has(> a.active) { /* styles to apply to the li tag */ }

所有主要浏览器都支持此选择器。请参阅https://caniuse.com/css-has检查您的目标浏览器或浏览器版本是否有支持它。


如果您的目标浏览器不完全支持此功能,您可能需要使用 JavaScript。

The W3C's Selectors Level 4 Working Draft includes a :has() pseudo-class that provides this capability, among others:

li:has(> a.active) { /* styles to apply to the li tag */ }

All major browsers support this selector. Refer to https://caniuse.com/css-has to check if your target browser or browser versions have support for it.


You may need to resort to using JavaScript if your target browser does not fully support this feature.

烟若柳尘 2025-01-27 05:36:27

我认为你不能只在 CSS 中选择父级。

但由于您似乎已经有一个 .active 类,因此将该类移动到 li (而不是 a)会更容易。这样您就可以仅通过 CSS 访问 lia

I don’t think you can select the parent in CSS only.

But as you already seem to have an .active class, it would be easier to move that class to the li (instead of the a). That way you can access both the li and the a via CSS only.

爱的那么颓废 2025-01-27 05:36:27

您可以使用此脚本

*! > input[type=text] { background: #000; }

这将选择文本输入的任何父。但是等等,还有更多。如果需要,可以选择一个指定的父:

.input-wrap! > input[type=text] { background: #000; }

或在活动处活动时选择它:

.input-wrap! > input[type=text]:focus { background: #000; }

查看此html:

<div class="input-wrap">
    <input type="text" class="Name"/>
    <span class="help hide">Your name sir</span>
</div>

您可以选择span.helpinput处于活动状态和显示:

.input-wrap! .help > input[type=text]:focus { display: block; }

还有更多功能;只需查看插件的文档即可。

顺便说一句,它在Internet&nbsp; Explorer中工作。

You can use this script:

*! > input[type=text] { background: #000; }

This will select any parent of a text input. But wait, there's still much more. If you want, you can select a specified parent:

.input-wrap! > input[type=text] { background: #000; }

Or select it when it's active:

.input-wrap! > input[type=text]:focus { background: #000; }

Check out this HTML:

<div class="input-wrap">
    <input type="text" class="Name"/>
    <span class="help hide">Your name sir</span>
</div>

You can select that span.help when the input is active and show it:

.input-wrap! .help > input[type=text]:focus { display: block; }

There are many more capabilities; just check out the documentation of the plugin.

BTW, it works in Internet Explorer.

情绪操控生活 2025-01-27 05:36:27

正如其他几个人所提到的,没有办法仅使用 CSS 来设置元素的父元素的样式,但以下内容适用于 jQuery

$("a.active").parents('li').css("property", "value");

As mentioned by a couple of others, there isn't a way to style an element's parent/s using just CSS but the following works with jQuery:

$("a.active").parents('li').css("property", "value");
痴者 2025-01-27 05:36:27

您可以使用 :has() 伪类(状态:工作草案规范MDNcaniuse) 为此:

li:has(> a.active) {
  outline: thin dotted red;
}
<ul>
  <li><a href="#">a</a></li>
  <li><a href="#" class="active">a.active</a></li>
  <li><a href="#">a</a></li>
</ul>

事实上,这个伪类可用于匹配具有特定元素作为子元素、孙子元素、下一个兄弟元素或后续兄弟元素的元素:

section, h1, p {
  font-size: 1rem;
  margin-top: 1rem;
  margin-bottom: 1rem;
}

h1:has(> .ref) {
  outline: thin dotted red;
}

h1:has(.ref) {
  outline: thin dotted red;
}

h1:has(+ .ref) {
  outline: thin dotted red;
}

h1:has(~ .ref) {
  outline: thin dotted red;
}
<section>
  <h1>
    heading
    <span class="ref">.ref</span>
  </h1>
</section>

<section>
  <h1>
    heading
    <span>
      span
      <span class="ref">.ref</span>
    </span>
  </h1>
</section>

<section>
  <h1>heading</h1>
  <p class="ref">.ref</p>
</section>

<section>
  <h1>heading</h1>
  <p>paragraph</p>
  <p class="ref">.ref</p>
</section>

我在原始答案中提出的问题仍然相关:

例如,如果您写道:

body:has(a.active) { 背景:红色; }

然后浏览器将不得不等待,直到它加载并解析
直到 来确定页面是否应该是红色的
或不。

You can use :has() pseudo-class (status: working draft, specifications, MDN, caniuse) for this:

li:has(> a.active) {
  outline: thin dotted red;
}
<ul>
  <li><a href="#">a</a></li>
  <li><a href="#" class="active">a.active</a></li>
  <li><a href="#">a</a></li>
</ul>

In fact, this pseudo-class can be used to match an element that has a specific element as child, grand child, next sibling or subsequent sibling:

section, h1, p {
  font-size: 1rem;
  margin-top: 1rem;
  margin-bottom: 1rem;
}

h1:has(> .ref) {
  outline: thin dotted red;
}

h1:has(.ref) {
  outline: thin dotted red;
}

h1:has(+ .ref) {
  outline: thin dotted red;
}

h1:has(~ .ref) {
  outline: thin dotted red;
}
<section>
  <h1>
    heading
    <span class="ref">.ref</span>
  </h1>
</section>

<section>
  <h1>
    heading
    <span>
      span
      <span class="ref">.ref</span>
    </span>
  </h1>
</section>

<section>
  <h1>heading</h1>
  <p class="ref">.ref</p>
</section>

<section>
  <h1>heading</h1>
  <p>paragraph</p>
  <p class="ref">.ref</p>
</section>

The concerns I raised in my original answer are still relevant:

For example, if you wrote:

body:has(a.active) { background: red; }

Then the browser will have to wait until it has loaded and parsed
everything until the </body> to determine if the page should be red
or not.

云仙小弟 2025-01-27 05:36:27

伪元素 :focus-within 允许在后代拥有焦点时选择父元素。

如果元素具有 tabindex 属性,则该元素可以获得焦点。

浏览器支持 focus-within

Tabindex

示例

.parent:focus-within {
  background: hsl(199deg, 65%, 73%);
}

/* demo styles */
body {
  margin: 0;
}
.parent {
  background: hsl(0, 0%, 80%);
  min-height: 100vh;
  display: grid;
  place-content: center;
}
.child {
  background: hsl(0, 0%, 0%);
  color: white;
  padding: 3rem;
  outline: 0;
  cursor: pointer;
  font: 18px/1.25 sans-serif;
  width: 20ch;
}
<div class="parent">
  <div class="child" tabindex="0">
    Click or Focus on me, my parent will change.
  </div>
</div>

The pseudo element :focus-within allows a parent to be selected if a descendent has focus.

An element can be focused if it has a tabindex attribute.

Browser support for focus-within

Tabindex

Example

.parent:focus-within {
  background: hsl(199deg, 65%, 73%);
}

/* demo styles */
body {
  margin: 0;
}
.parent {
  background: hsl(0, 0%, 80%);
  min-height: 100vh;
  display: grid;
  place-content: center;
}
.child {
  background: hsl(0, 0%, 0%);
  color: white;
  padding: 3rem;
  outline: 0;
  cursor: pointer;
  font: 18px/1.25 sans-serif;
  width: 20ch;
}
<div class="parent">
  <div class="child" tabindex="0">
    Click or Focus on me, my parent will change.
  </div>
</div>

二智少女 2025-01-27 05:36:27

在CSS&nbsp; 2中​​没有办法这样做。您可以将类添加到li中,并引用a

li.active > a {
    property: value;
}

There isn't a way to do this in CSS 2. You could add the class to the li and reference the a:

li.active > a {
    property: value;
}
裸钻 2025-01-27 05:36:27

尝试将 a 切换为 block 显示,然后使用您想要的任何样式。 a 元素将填充 li 元素,您将能够根据需要修改其外观。不要忘记将 li padding 设置为 0。

li {
  padding: 0;
  overflow: hidden;
}
a {
  display: block;
  width: 100%;
  color: ..., background: ..., border-radius: ..., etc...
}
a.active {
  color: ..., background: ...
}

Try to switch a to block display, and then use any style you want. The a element will fill the li element, and you will be able to modify its look as you want. Don't forget to set li padding to 0.

li {
  padding: 0;
  overflow: hidden;
}
a {
  display: block;
  width: 100%;
  color: ..., background: ..., border-radius: ..., etc...
}
a.active {
  color: ..., background: ...
}
我们的影子 2025-01-27 05:36:27

在 CSS Selectors 4 规范中,CSS 引入了一个名为 :has() 的新选择器,它最终让我们可以选择父级。这意味着我们将能够定位一个包含特定子元素的 CSS 元素。 Safari 和 Chrome 105 均已支持此功能。显示了完整的支持表
此处

父选择器的工作原理

在 CSS 中,如果我们想要选择某些内容,我们可以使用沿 DOM 向下排列的选择器。

例如,在 div 标记中选择 ap 标记如下所示:

 div p {
   color: red;
}

到目前为止,无法真正选择其中包含 p 标记的 div 标记,但是,这意味着我们必须求助于Javascript。这没有在 CSS 中实现的主要原因是它是一个相当昂贵的操作。 CSS 的解析速度相对较快,但选择父标签需要相对大量的处理。

使用 :has 选择器,我们现在可以选择具有 p 子元素的 div 元素,或者选择器的任何正常组合。

例如,选择带有子 pdiv 现在看起来像这样:

div:has(p) {
  color: red;
}

这将使任何带有子 pdiv代码>红色。

将父级选择与其他选择器相结合

就像任何其他 CSS 选择器一样,我们可以针对特定情况将其结合起来。
例如,如果您只想选择具有直接 span 子级的 div 标签:

div:has(> span) {
  color: red;
}

正如 :has 的词汇所建议的那样,它不仅仅是仅限于家长选择。

例如,下面我们可以选择一个 span,其中 :has 有一个同级 div

span:has(+ div) {
color: red;
}

或者甚至选择一个没有子元素的元素,通过使用 :not() 选择器。

例如,下面的代码将选择任何没有 ap 子元素的 div:

div:not(:has(p)) {
 color: red;
}

选择 CSS 中仅包含文本的元素

CSS 中一个非常常见的问题是 :empty 标签不会选择包含任何内容的元素text - 因此有时一个元素可以包含一个空格,并且 :empty 将不适用。 :has 选择器使我们能够选择仅包含文本节点且不包含其他子元素的元素。

虽然这对于带有空格的简单 :empty 元素来说并不是完美的解决方案(因为这将选择仅包含文本且没有其他 HTML DOM 元素的任何元素),但它确实使我们能够选择带有空格的 DOM 元素只有文本节点,这在以前是不可能的。我们可以通过以下代码来实现这一点:

div:not(:has(*)) {
  background: green;
}

In the CSS Selectors 4 specification, CSS introduces a new selector called :has(), which finally lets us select parents. That means is we’ll be able to target a CSS element that has specific children within it. This is already supported in Safari and is also in Chrome 105. The full support table is shown
here.

Parent Selectors workings

In CSS, if we want to select something, we use selectors that descend the DOM.

For example, selecting a p tag within a div tag looks like this:

 div p {
   color: red;
}

Until now, couldn’t really select the div tags which had p tags within them, though, and this meant we had to resort to Javascript. The main reason this wasn’t implemented in CSS is that it’s quite an expensive operation to do. CSS is relatively fast to parse, but selecting parent tags requires a relatively significantly larger amount of processing.

Using the :has selector, we can now select div elements which have a p children, or any normal combination of selectors.

For example, selecting a div with a child p now looks like this:

div:has(p) {
  color: red;
}

This will make any div with a child p red.

Combining parent selection with other selectors

Just like any other CSS selector, we can combine this for specific circumstances.
For example, if you want to select only div tags which have direct span children:

div:has(> span) {
  color: red;
}

As the vocabulary of :has suggested, it is not just limited to parent selection.

For example, below we can select a span which :has a sibling div:

span:has(+ div) {
color: red;
}

Or even, selecting an element which does not have a child, by using the :not() selector.

For example, the following will select any div which does not have a p child:

div:not(:has(p)) {
 color: red;
}

Selecting elements that only contain text in CSS

One very common problem in CSS is that the :empty tag does not select elements that contain any text - so sometimes an element can contain one space, and :empty will not apply. The :has selector gives us the power to select elements that only contain text nodes and no other child elements.

Although this is not the perfect solution for simply :empty elements with spaces (as this will select any element with just text and no additional HTML DOM elements) - it does give us the ability to select DOM elements with only text nodes, which was not previously possible. We can achieve this with the following code:

div:not(:has(*)) {
  background: green;
}
呆萌少年 2025-01-27 05:36:27

CSS 选择器“General Sibling Combinator”可能用于什么您想要的:

E ~ F {
    property: value;
}

这与前面有 E 元素的任何 F 元素匹配。

The CSS selector “General Sibling Combinator” could maybe used for what you want:

E ~ F {
    property: value;
}

This matches any F element that is preceded by an E element.

岁吢 2025-01-27 05:36:27

这是选择器级别4 规范的最讨论的方面。这样,选择器将能够使用:has()来根据其孩子为元素进行样式。

例如:

body:has(a:hover) {
   background: red;
}

如果用户徘徊在任何锚点上,将设置红色背景色。

This is the most discussed aspect of the Selectors Level 4 specification. With this, a selector will be able to style an element according to its child by using :has().

For example:

body:has(a:hover) {
   background: red;
}

will set a red background-color if the user hovers over any anchor.

感悟人生的甜 2025-01-27 05:36:27

据我所知,CSS 2 中没有。 CSS 3 具有更强大的选择器,但并非在所有浏览器上一致实现。即使使用改进的选择器,我也不相信它能够完全完成您在示例中指定的内容。

Not in CSS 2 as far as I'm aware. CSS 3 has more robust selectors but is not consistently implemented across all browsers. Even with the improved selectors, I don't believe it will accomplish exactly what you've specified in your example.

梦回旧景 2025-01-27 05:36:27

我知道OP正在寻找CSS解决方案,但使用jQuery实现很容易。在我的情况下,我需要找到&lt; ul&gt; parent tag的parent tag,以适用于&lt; span&gt;标签,子&lt; li&gt; 。 jQuery具有:has选择器,因此可以通过其中包含的孩子识别父母:

$("ul:has(#someId)")

将选择具有ul元素,该元素的元素具有ID someid someid < /em>。或回答原始问题,以下问题应该可以解决问题(未经测试):

$("li:has(.active)")

I know the OP was looking for a CSS solution but it is simple to achieve using jQuery. In my case I needed to find the <ul> parent tag for a <span> tag contained in the child <li>. jQuery has the :has selector so it's possible to identify a parent by the children it contains:

$("ul:has(#someId)")

will select the ul element that has a child element with id someId. Or to answer the original question, something like the following should do the trick (untested):

$("li:has(.active)")
多像笑话 2025-01-27 05:36:27

您可以尝试使用超链接作为父级,然后在悬停时更改内部元素。像这样:

a.active h1 {color:red;}

a.active:hover h1 {color:green;}

a.active h2 {color:blue;}

a.active:hover h1 {color:yellow;}

通过这种方式,您可以根据父元素的翻转来更改多个内部标签中的样式。

You might try to use hyperlink as the parent, and then change the inner elements on hover. Like this:

a.active h1 {color:red;}

a.active:hover h1 {color:green;}

a.active h2 {color:blue;}

a.active:hover h1 {color:yellow;}

This way you can change the style in multiple inner tags, based on the rollover of the parent element.

情绪 2025-01-27 05:36:27

这是使用Pointer-events的黑客攻击,悬停

<!doctype html>
<html>
    <head>
        <title></title>
        <style>
/* accessory */
.parent {
    width: 200px;
    height: 200px;
    background: gray;
}
.parent, 
.selector {
    display: flex;
    justify-content: center;
    align-items: center;
}
.selector {
    cursor: pointer;
    background: silver;
    width: 50%;
    height: 50%;
}
        </style>
        <style>
/* pertinent */
.parent {
    background: gray;
    pointer-events: none;
}
.parent:hover {
    background: fuchsia;
}
.parent 
.selector {
    pointer-events: auto;
}
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="selector"></div>
        </div>
    </body>
</html>

Here's a hack using pointer-events with hover:

<!doctype html>
<html>
    <head>
        <title></title>
        <style>
/* accessory */
.parent {
    width: 200px;
    height: 200px;
    background: gray;
}
.parent, 
.selector {
    display: flex;
    justify-content: center;
    align-items: center;
}
.selector {
    cursor: pointer;
    background: silver;
    width: 50%;
    height: 50%;
}
        </style>
        <style>
/* pertinent */
.parent {
    background: gray;
    pointer-events: none;
}
.parent:hover {
    background: fuchsia;
}
.parent 
.selector {
    pointer-events: auto;
}
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="selector"></div>
        </div>
    </body>
</html>

遥远的绿洲 2025-01-27 05:36:27

CSS 父选择器(也称为 :has() 选择器)终于登陆 Safari TP 137。该功能目前也在 Chrome 中实现。 (MDN 文档

父级选择是通过伪类 完成的:has()。例如,div:has(> .child) 将选择所有

元素,其中子元素具有 child 类。

其他示例:

选择元素的直接父元素

<div>
  <p>Child Element</p>
</div>
div:has(> p)

选择元素的所有父元素

<div id="grandparent">
      <div id="parent">
            <div id="child"></div>
      <div>
</div>

以下选择器将选择 grandparentparent

div:has(.child)

您还可以将其用于嵌套选择器,甚至与其他伪选择器一起使用类:

div:has(> :nth-child(10))

其他有效的 CSS 运算符可用于自定义查询。

请密切关注 caniuse.com/css-has 以了解浏览器兼容性。

The CSS parent selector (also know as the :has() selector) has finally landed in Safari TP 137. The feature is currently being implementated in Chrome as well. (MDN Documentation)

Parent selection is done via the pseudo-class :has(). For example, div:has(> .child) will select all <div> elements with a child having a child class.

Other examples:

Selecting direct parent of an element

<div>
  <p>Child Element</p>
</div>
div:has(> p)

Selecting all the parents of an element

<div id="grandparent">
      <div id="parent">
            <div id="child"></div>
      <div>
</div>

The following selector will select both grandparent and parent

div:has(.child)

You can also use it for nested selectors and even with other pseudo classes:

div:has(> :nth-child(10))

Other valid CSS operators can be used to customize the query.

Keep an eye on caniuse.com/css-has for browser compatibility.

自此以后,行同陌路 2025-01-27 05:36:27

目前没有父选择器和父选择器。它甚至没有在 W3C 的任何讨论中被讨论。您需要了解浏览器如何评估 CSS,才能真正了解我们是否需要它。

这里有很多技术解释。

Jonathan Snook 解释了 CSS 的评估方式

Chris Coyier 谈论父选择器

Harry Roberts 再次讲述如何编写高效的 CSS 选择器

但是 Nicole Sullivan 有一些关于积极趋势的有趣事实

这些人都是前端开发领域的顶尖人才。

Currently there is no parent selector & it is not even being discussed in any of the talks of W3C. You need to understand how CSS is evaluated by the browser to actually understand if we need it or not.

There is a lot of technical explanation here.

Jonathan Snook explains how CSS is evaluated.

Chris Coyier on the talks of Parent selector.

Harry Roberts again on writing efficient CSS selectors.

But Nicole Sullivan has some interesting facts on positive trends.

These people are all top class in the field of front end development.

∝单色的世界 2025-01-27 05:36:27

只是水平菜单的一个想法...

HTML 的一部分

<div class='list'>
  <div class='item'>
    <a>Link</a>
  </div>
  <div class='parent-background'></div>
  <!-- submenu takes this place -->
</div>

CSS 的一部分

/* Hide parent backgrounds... */
.parent-background {
  display: none; }

/* ... and show it when hover on children */
.item:hover + .parent-background {
  display: block;
  position: absolute;
  z-index: 10;
  top: 0;
  width: 100%; }

更新了演示和其余代码

另一个示例如何将其与文本输入一起使用 - 选择父字段集

Just an idea for horizontal menu...

Part of HTML

<div class='list'>
  <div class='item'>
    <a>Link</a>
  </div>
  <div class='parent-background'></div>
  <!-- submenu takes this place -->
</div>

Part of CSS

/* Hide parent backgrounds... */
.parent-background {
  display: none; }

/* ... and show it when hover on children */
.item:hover + .parent-background {
  display: block;
  position: absolute;
  z-index: 10;
  top: 0;
  width: 100%; }

Updated demo and the rest of code

Another example how to use it with text-inputs - select parent fieldset

所有深爱都是秘密 2025-01-27 05:36:27

有一个插件扩展了CSS,以包含一些非标准功能,这些功能在设计网站时确实可以提供帮助。称为 eqcss

EQCS添加的一件事是父选择器。它可以在所有浏览器,Internet&nbsp; Explorer&nbsp; 8及以上工作。这是格式:

@element 'a.active' {
  $parent {
    background: red;
  }
}

因此,在这里,我们已经在每个元素上打开了一个元素查询A.Active,并且对于该查询的样式,$ parent之类的东西很有意义,因为有一个参考点。浏览器可以找到父,因为它与JavaScript中的parentnode非常相似。

这是$ parent 另一个$ parent demo 在Internet上工作的演示&nbsp; explorer&nbsp; 8 ,以及如果您没有Internet&nbsp; explorer&nbsp; nbsp; 8周围的屏幕截图可与进行测试。

eqcss还包括 meta-selectors $ prev for a e元素之前的元素选择的元素和$ this仅适用于匹配元素查询的元素等等。

There's a plugin that extends CSS to include some non-standard features that can really help when designing websites. It's called EQCSS.

One of the things EQCSS adds is a parent selector. It works in all browsers, Internet Explorer 8 and up. Here's the format:

@element 'a.active' {
  $parent {
    background: red;
  }
}

So here we've opened an element query on every element a.active, and for the styles inside that query, things like $parent make sense, because there's a reference point. The browser can find the parent, because it's very similar to parentNode in JavaScript.

Here's a demo of $parent and another $parent demo that works in Internet Explorer 8, as well as a screenshot in case you don't have Internet Explorer 8 around to test with.

EQCSS also includes meta-selectors: $prev for the element before a selected element and $this for only those elements that match an element query, and more.

孤独患者 2025-01-27 05:36:27

现在是2019年, CSS嵌套模块的最新草稿实际上具有这样的东西。引入@nest atrules。

3.2。嵌套处:@nest

直接嵌套看起来不错,但有些脆弱。某些有效的嵌套选择器(例如.foo&amp; to and to n of to n of。&amp; amp; amp; amp; amp; amp; amp;同样,有些人发现筑巢具有挑战性,可以视觉与周围的声明区分开。

为了帮助所有这些问题,此规范定义了@nest规则,该规则对如何有效嵌套样式规则施加更少的限制。它的语法为:

@nest = @nest&lt; selector&gt; {&lt;声明列表&gt; }

@nest规则与样式规则相同的功能:它以选择器开头,并包含适用于选择器匹配元素的声明。唯一的区别是,@nest规则中使用的选择器必须是嵌套的,这意味着它在其中包含嵌套选择器。如果选择器的所有单个复杂选择器都在巢中,则选择巢的列表。

(从上面的URL复制和粘贴)。

根据此规范的有效选择器的示例:

.foo {
  color: red;
  @nest & > .bar {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   .foo > .bar { color: blue; }
 */

.foo {
  color: red;
  @nest .parent & {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   .parent .foo { color: blue; }
 */

.foo {
  color: red;
  @nest :not(&) {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   :not(.foo) { color: blue; }
 */

It's now 2019, and the latest draft of the CSS Nesting Module actually has something like this. Introducing @nest at-rules.

3.2. The Nesting At-Rule: @nest

While direct nesting looks nice, it is somewhat fragile. Some valid nesting selectors, like .foo &, are disallowed, and editing the selector in certain ways can make the rule invalid unexpectedly. As well, some people find the nesting challenging to distinguish visually from the surrounding declarations.

To aid in all these issues, this specification defines the @nest rule, which imposes fewer restrictions on how to validly nest style rules. Its syntax is:

@nest = @nest <selector> { <declaration-list> }

The @nest rule functions identically to a style rule: it starts with a selector, and contains declarations that apply to the elements the selector matches. The only difference is that the selector used in a @nest rule must be nest-containing, which means it contains a nesting selector in it somewhere. A list of selectors is nest-containing if all of its individual complex selectors are nest-containing.

(Copy and pasted from the URL above).

Example of valid selectors under this specification:

.foo {
  color: red;
  @nest & > .bar {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   .foo > .bar { color: blue; }
 */

.foo {
  color: red;
  @nest .parent & {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   .parent .foo { color: blue; }
 */

.foo {
  color: red;
  @nest :not(&) {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   :not(.foo) { color: blue; }
 */
秋风の叶未落 2025-01-27 05:36:27

W3C不包括这样的选择器,因为它会对浏览器产生巨大的性能影响。

The W3C excluded such a selector because of the huge performance impact it would have on a browser.

╭⌒浅淡时光〆 2025-01-27 05:36:27

从技术上讲,没有直接的方法可以做到这一点。不过,您可以使用 jQuery 或 JavaScript 来解决这个问题。

但是,您也可以做这样的事情。

a.active h1 {color: blue;}
a.active p {color: green;}

jQuery

$("a.active").parents('li').css("property", "value");

如果您想使用 jQuery 实现此目的,这里是 jQuery 父选择器

Technically there is no direct way to do this. However, you can sort that out with either jQuery or JavaScript.

However, you can do something like this as well.

a.active h1 {color: blue;}
a.active p {color: green;}

jQuery

$("a.active").parents('li').css("property", "value");

If you want to achieve this using jQuery here is the reference for the jQuery parent selector.

萌无敌 2025-01-27 05:36:27

简短的答案是 no ;在此阶段,我们在CSS中没有parent selector,但是如果您不必交换元素或类,则第二个选项是使用JavaScript。这样的东西:

var activeATag = Array.prototype.slice.call(document.querySelectorAll('a.active'));

activeATag.map(function(x) {
  if(x.parentNode.tagName === 'LI') {
    x.parentNode.style.color = 'red'; // Your property: value;
  }
});

或者,如果您在应用程序中使用 jQuery ,则是一种较短的方法:

$('a.active').parents('li').css('color', 'red'); // Your property: value;

The short answer is NO; we don't have a parent selector at this stage in CSS, but if you don't have to swap the elements or classes anyway, the second option is using JavaScript. Something like this:

var activeATag = Array.prototype.slice.call(document.querySelectorAll('a.active'));

activeATag.map(function(x) {
  if(x.parentNode.tagName === 'LI') {
    x.parentNode.style.color = 'red'; // Your property: value;
  }
});

Or a shorter way if you use jQuery in your application:

$('a.active').parents('li').css('color', 'red'); // Your property: value;
撩起发的微风 2025-01-27 05:36:27

虽然目前标准CSS中没有父选择器,但我正在开发一个名为axe(即增强CSS选择器语法/ ACSSSS)的(个人)项目,其中它的 7 个新选择器,包括:

  1. 直接父级 选择器 <(可实现与 > 相反的选择)和
  2. 任意祖先选择器 ^(可实现与[SPACE]相反的选择)

axe目前处于相对早期的BETA开发阶段。

在这里查看演示:

.parent {
  float: left;
  width: 180px;
  height: 180px;
  margin-right: 12px;
  background-color: rgb(191, 191, 191);
}

.child {
  width: 90px;
  height: 90px;
  margin: 45px;
  padding-top: 12px;
  font-family: sans-serif;
  text-align: center;
  font-size: 12px;
  background-color: rgb(255, 255, 0);
}

.child.using-axe < .parent {
  background-color: rgb(255, 0, 0);
}
<div class="parent">
  <div class="child"></div>
</div>

<div class="parent">
  <div class="child using-axe">Here, the axe parent selector turns the outer square red.</div>
</div>


<script src="https://rouninmedia.github.io/axe/axe.js"></script>

在上面的示例中,<直接父选择器,因此

  • .child.using-axe < .parent

表示:

.child.using-axe 的任何直接父级,即 .parent

您也可以使用:

  • .child.using-axe .child.using-axe .child.using-axe .child.using-axe .child.using-axe .parent div

这意味着:

.child.using-axe 的任何直接父级,它是一个 div

Although there is no parent selector in standard CSS at present, I am working on a (personal) project called axe (ie. Augmented CSS Selector Syntax / ACSSSS) which, among its 7 new selectors, includes both:

  1. an immediate parent selector < (which enables the opposite selection to >)
  2. an any ancestor selector ^ (which enables the opposite selection to [SPACE])

axe is presently in a relatively early BETA stage of development.

See a demo here:

.parent {
  float: left;
  width: 180px;
  height: 180px;
  margin-right: 12px;
  background-color: rgb(191, 191, 191);
}

.child {
  width: 90px;
  height: 90px;
  margin: 45px;
  padding-top: 12px;
  font-family: sans-serif;
  text-align: center;
  font-size: 12px;
  background-color: rgb(255, 255, 0);
}

.child.using-axe < .parent {
  background-color: rgb(255, 0, 0);
}
<div class="parent">
  <div class="child"></div>
</div>

<div class="parent">
  <div class="child using-axe">Here, the axe parent selector turns the outer square red.</div>
</div>


<script src="https://rouninmedia.github.io/axe/axe.js"></script>

In the example above < is the immediate parent selector, so

  • .child.using-axe < .parent

means:

any immediate parent of .child.using-axe which is .parent

You could alternatively use:

  • .child.using-axe < div

which would mean:

any immediate parent of .child.using-axe which is a div

青巷忧颜 2025-01-27 05:36:27

编辑2024-10-15

现在有一个:has() css功能,除非无法实现所需结果,否则应忽略以下结果!因为内容仅出于历史原因而保留。


有什么想法?

如果CSS4将一些钩子添加到中,它将很喜欢。在此之前 to break 事物连接的通常方式,这也允许CSS在其正常范围之外运行...

/* Hide things that may be latter shown */
.menu__checkbox__selection,
.menu__checkbox__style,
.menu__hidden {
  display: none;
  visibility: hidden;
  opacity: 0;
  filter: alpha(opacity=0); /* Old Microsoft opacity */
}


/* Base style for content and style menu */
.main__content {
  background-color: lightgray;
  color: black;
}

.menu__hidden {
  background-color: black;
  color: lightgray;
  /* Make list look not so _listy_ */
  list-style: none;
  padding-left: 5px;
}

.menu__option {
  box-sizing: content-box;
  display: block;
  position: static;
  z-index: auto;
}

/* ▼ - \u2630 - Three Bars */
/*
.menu__trigger__selection::before {
  content: '\2630';
  display: inline-block;
}
*/

/* ▼ - Down Arrow */
.menu__trigger__selection::after {
  content: "\25BC";
  display: inline-block;
  transform: rotate(90deg);
}


/* Customize to look more `select` like if you like */
.menu__trigger__style:hover,
.menu__trigger__style:active {
  cursor: pointer;
  background-color: darkgray;
  color: white;
}


/**
 * Things to do when checkboxes/radios are checked
 */

.menu__checkbox__selection:checked + .menu__trigger__selection::after,
.menu__checkbox__selection[checked] + .menu__trigger__selection::after {
  transform: rotate(0deg);
}

/* This bit is something that you may see elsewhere */
.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
  display: block;
  visibility: visible;
  opacity: 1;
  filter: alpha(opacity=100); /* Microsoft!? */
}


/**
 * Hacky CSS only changes based off non-inline checkboxes
 * ... AKA the stuff you cannot unsee after this...
 */
.menu__checkbox__style[id="style-default"]:checked ~ .main__content {
  background-color: lightgray;
  color: black;
}

.menu__checkbox__style[id="style-default"]:checked ~ .main__content .menu__trigger__style[for="style-default"] {
  color: darkorange;
}

.menu__checkbox__style[id="style-one"]:checked ~ .main__content {
  background-color: black;
  color: lightgray;
}

.menu__checkbox__style[id="style-one"]:checked ~ .main__content .menu__trigger__style[for="style-one"] {
  color: darkorange;
}

.menu__checkbox__style[id="style-two"]:checked ~ .main__content {
  background-color: darkgreen;
  color: red;
}

.menu__checkbox__style[id="style-two"]:checked ~ .main__content .menu__trigger__style[for="style-two"] {
  color: darkorange;
}
<!--
  This bit works, but will one day cause troubles,
  but truth is you can stick checkbox/radio inputs
  just about anywhere and then call them by id with
  a `for` label. Keep scrolling to see what I mean
-->
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-default">
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-one">
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-two">


<div class="main__content">

  <p class="paragraph__split">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
  </p>

  <input type="checkbox"
         class="menu__checkbox__selection"
         id="trigger-style-menu">
  <label for="trigger-style-menu"
         class="menu__trigger__selection"> Theme</label>

  <ul class="menu__hidden">
    <li class="menu__option">
      <label for="style-default"
             class="menu__trigger__style">Default Style</label>
    </li>

    <li class="menu__option">
      <label for="style-one"
             class="menu__trigger__style">First Alternative Style</label>
    </li>

    <li class="menu__option">
      <label for="style-two"
             class="menu__trigger__style">Second Alternative Style</label>
    </li>
  </ul>

  <p class="paragraph__split">
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>

</div>

... Pretty Gross ,但是只有CSS和HTML,除了Body and :root从几乎可以通过链接IDradio> radio>的属性/复选框 input输入 输入 /code> s label 触发器;可能有人会在某个时候展示如何重新触发这些。

另一个警告是,特定 的特定id也许可以使用,第一个复选框/无线电 wins 换句话说... 但是多个标签都可以指向相同的input,尽管这会使HTML和CSS看上去甚至更加粗糙。


...我希望有某种解决方法存在于CSS 2级...

我不确定其他伪类课程,但是我:检查 for Pre-css&nbsp; 3。如果我没记错的话,那就是[检查],这就是为什么您可以在上面的代码中找到它的原因,例如

.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
 /* rules: and-stuff; */
}

...但是对于:: efter 和:悬停,我完全不确定CSS版本最初出现的哪个版本。

这一切都说明了,请不要在生产中使用它,甚至不是愤怒。肯定的是一个笑话,或者换句话说,仅仅因为可以完成的事情并不总是意味着应该

Edit 2024-10-15

There is now a :has() CSS feature and, unless that fails to achieve the desired results, the following should be ignored! Because content remains mainly for historical reasons only.


Any ideas?

CSS4 will be fancy if it adds some hooks into walking backwards. Until then it is possible (though not advisable) to use checkbox and/or radio inputs to break the usual way that things are connected, and through that also allow CSS to operate outside of its normal scope...

/* Hide things that may be latter shown */
.menu__checkbox__selection,
.menu__checkbox__style,
.menu__hidden {
  display: none;
  visibility: hidden;
  opacity: 0;
  filter: alpha(opacity=0); /* Old Microsoft opacity */
}


/* Base style for content and style menu */
.main__content {
  background-color: lightgray;
  color: black;
}

.menu__hidden {
  background-color: black;
  color: lightgray;
  /* Make list look not so _listy_ */
  list-style: none;
  padding-left: 5px;
}

.menu__option {
  box-sizing: content-box;
  display: block;
  position: static;
  z-index: auto;
}

/* ▼ - \u2630 - Three Bars */
/*
.menu__trigger__selection::before {
  content: '\2630';
  display: inline-block;
}
*/

/* ▼ - Down Arrow */
.menu__trigger__selection::after {
  content: "\25BC";
  display: inline-block;
  transform: rotate(90deg);
}


/* Customize to look more `select` like if you like */
.menu__trigger__style:hover,
.menu__trigger__style:active {
  cursor: pointer;
  background-color: darkgray;
  color: white;
}


/**
 * Things to do when checkboxes/radios are checked
 */

.menu__checkbox__selection:checked + .menu__trigger__selection::after,
.menu__checkbox__selection[checked] + .menu__trigger__selection::after {
  transform: rotate(0deg);
}

/* This bit is something that you may see elsewhere */
.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
  display: block;
  visibility: visible;
  opacity: 1;
  filter: alpha(opacity=100); /* Microsoft!? */
}


/**
 * Hacky CSS only changes based off non-inline checkboxes
 * ... AKA the stuff you cannot unsee after this...
 */
.menu__checkbox__style[id="style-default"]:checked ~ .main__content {
  background-color: lightgray;
  color: black;
}

.menu__checkbox__style[id="style-default"]:checked ~ .main__content .menu__trigger__style[for="style-default"] {
  color: darkorange;
}

.menu__checkbox__style[id="style-one"]:checked ~ .main__content {
  background-color: black;
  color: lightgray;
}

.menu__checkbox__style[id="style-one"]:checked ~ .main__content .menu__trigger__style[for="style-one"] {
  color: darkorange;
}

.menu__checkbox__style[id="style-two"]:checked ~ .main__content {
  background-color: darkgreen;
  color: red;
}

.menu__checkbox__style[id="style-two"]:checked ~ .main__content .menu__trigger__style[for="style-two"] {
  color: darkorange;
}
<!--
  This bit works, but will one day cause troubles,
  but truth is you can stick checkbox/radio inputs
  just about anywhere and then call them by id with
  a `for` label. Keep scrolling to see what I mean
-->
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-default">
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-one">
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-two">


<div class="main__content">

  <p class="paragraph__split">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
  </p>

  <input type="checkbox"
         class="menu__checkbox__selection"
         id="trigger-style-menu">
  <label for="trigger-style-menu"
         class="menu__trigger__selection"> Theme</label>

  <ul class="menu__hidden">
    <li class="menu__option">
      <label for="style-default"
             class="menu__trigger__style">Default Style</label>
    </li>

    <li class="menu__option">
      <label for="style-one"
             class="menu__trigger__style">First Alternative Style</label>
    </li>

    <li class="menu__option">
      <label for="style-two"
             class="menu__trigger__style">Second Alternative Style</label>
    </li>
  </ul>

  <p class="paragraph__split">
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>

</div>

... pretty gross, but with just CSS and HTML it is possible to touch and re-touch anything but the body and :root from just about anywhere by linking the id and for properties of radio/checkbox inputs and label triggers; likely someone'll show how to re-touch those at some point.

One additional caveat is that only one input of a specific id maybe used, first checkbox/radio wins a toggled state in other words... But multiple labels can all point to the same input, though that would make both the HTML and CSS look even grosser.


... I'm hoping that there is some sort of workaround that exists native to CSS Level 2...

I am not sure about the other pseudo classes, but I :checked for pre-CSS 3. If I remember correctly, it was something like [checked] which is why you may find it in the above code, for example,

.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
 /* rules: and-stuff; */
}

... but for things like ::after and :hover, I'm not at all certain in which CSS version those first appeared.

That all stated, please don't ever use this in production, not even in anger. As a joke sure, or in other words just because something can be done does not always mean it should.

浮云落日 2025-01-27 05:36:27

尝试这个...

该解决方案使用没有JavaScript的普通CSS2规则,并且可以在所有浏览器(新旧)中工作。单击时,儿童标签会激活其活动伪级事件。然后,它简单地隐藏自身,允许活动事件起泡到父li标签,然后将自己重新安排并以新样式揭示自己的锚点。孩子为父母设计了样式。

使用您的示例:

<ul>
    <li class="listitem">
        <a class="link" href="#">This is a Link</a>
    </li>
</ul>

现在,将这些样式与活动 a上的伪级应用于链接时 a retyle li 标记链接时,请单击链接

a.link {
    display: inline-block;
    color: white;
    background-color: green;
    text-decoration: none;
    padding: 5px;
}

li.listitem {
    display: inline-block;
    margin: 0;
    padding: 0;
    background-color: transparent;
}

/* When this 'active' pseudo-class event below fires on click, it hides itself,
triggering the active event again on its parent which applies new styles to itself and its child. */

a.link:active {
    display: none;
}

.listitem:active {
    background-color: blue;
}

.listitem:active a.link {
    display: inline-block;
    background-color: transparent;
}

:现在应该看到带有绿色背景的链接,现在可以在单击时更改为列表项目的蓝色背景。

转到

”“在此处输入图像说明”

单击。

Try this...

This solution uses plain CSS2 rules with no Javascript and works in all browsers, old and new. When clicked, the child anchor tag activates its active pseudo-class event. It then simply hides itself, allowing the active event to bubble up to the parent li tag who then restyles himself and reveals his anchor child again with a new style. The child has styled the parent.

Using your example:

<ul>
    <li class="listitem">
        <a class="link" href="#">This is a Link</a>
    </li>
</ul>

Now apply these styles with the active pseudo-class on a to restyle the parent li tag when the link is clicked:

a.link {
    display: inline-block;
    color: white;
    background-color: green;
    text-decoration: none;
    padding: 5px;
}

li.listitem {
    display: inline-block;
    margin: 0;
    padding: 0;
    background-color: transparent;
}

/* When this 'active' pseudo-class event below fires on click, it hides itself,
triggering the active event again on its parent which applies new styles to itself and its child. */

a.link:active {
    display: none;
}

.listitem:active {
    background-color: blue;
}

.listitem:active a.link {
    display: inline-block;
    background-color: transparent;
}

You should see the link with a green background now change to the list item's blue background on click.

enter image description here

turns to

enter image description here

on click.

离鸿 2025-01-27 05:36:27

目前,只有当父元素中有 元素时,才能根据子元素更改父元素。当输入获得焦点时,其相应的父元素可能会使用 CSS 受到影响。

以下示例将帮助您了解在 CSS 中使用 :focus-within

.outer-div {
  width: 400px;
  height: 400px;
  padding: 50px;
  float: left
}

.outer-div:focus-within {
  background: red;
}

.inner-div {
  width: 200px;
  height: 200px;
  float: left;
  background: yellow;
  padding: 50px;
}
<div class="outer-div">
  <div class="inner-div">
    I want to change outer-div(Background color) class based on inner-div. Is it possible?
    <input type="text" placeholder="Name" />
  </div>
</div>

Changing parent element based on child element can currently only happen when we have an <input> element inside the parent element. When an input gets focus, its corresponding parent element can get affected using CSS.

Following example will help you understand using :focus-within in CSS.

.outer-div {
  width: 400px;
  height: 400px;
  padding: 50px;
  float: left
}

.outer-div:focus-within {
  background: red;
}

.inner-div {
  width: 200px;
  height: 200px;
  float: left;
  background: yellow;
  padding: 50px;
}
<div class="outer-div">
  <div class="inner-div">
    I want to change outer-div(Background color) class based on inner-div. Is it possible?
    <input type="text" placeholder="Name" />
  </div>
</div>

韬韬不绝 2025-01-27 05:36:27

不,您不能仅在CSS中选择父。

但是,由于您似乎已经拥有一个Activive类,因此将该类移动到li(而不是a)会更容易。这样,您只能通过CSS访问lia

No, you cannot select the parent in CSS only.

But as you already seem to have an .active class, it would be easier to move that class to the li (instead of the a). That way you can access both the li and the a via CSS only.

花开柳相依 2025-01-27 05:36:27

由于“ CSS工作组先前拒绝父级选择器的建议的主要原因与浏览器性能和增量渲染问题有关”,因此没有CSS(因此在CSS预处理器中)父级选择器。

There no css (and therefore in css preprocessors) parent selector due to "The major reasons for the CSS Working Group previously rejecting proposals for parent selectors are related to browser performance and incremental rendering issues."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文