CSS:仅当存在较晚的兄弟时才选择元素

2022-01-10 00:00:00 css-selectors javascript html css

在我的 HTML 结构中,我是这样设置的:

In my HTML structure, I have it set up like this:

<body>
   <main>
      <section>
      ...
      </section>

      <aside>
      ...
      </aside>
   </main>
</body>

问题是,并不是所有页面都有<aside>

The problem is, not all pages have <aside>

我需要选择 <section> 并给它一个 max-width: 500px; 仅当 <aside> 存在.默认为 section { max-width: 1000px;}(当 <aside> 不存在时)

I need to select <section> and give it a max-width: 500px; ONLY when <aside> is present. The default is section { max-width: 1000px; } (when <aside> is absent)

不同于 一个标签的选择器,后跟另一个标签;用户 [提出问题] 想要始终设置B"样式.此外,在这个问题中,用户想要选择B"(而不是A")

Unlike in Selector for one tag directly followed by another tag; the user [asking the question] wants to style "B" ALL the time. Also, in this question, the user wants to select "B" (not "A")

  • 仅当 <aside> 存在时,我才需要设置 <section> 样式.
  • 我无法更改 HTML 的顺序 >_<
  • 只能用 CSS 完成吗?
  • 我需要什么选择器或如何设置它?
  • 如果不能用 CSS 完成(我宁愿它只是 CSS),我该如何完成?
  • I need to style <section> ONLY if <aside> is present.
  • I can't change the order of the HTML >_<
  • Can it be done with CSS only?
  • What selector do I need or how to set it up?
  • If it can't be done with CSS (I rather it be CSS-only), how can I accomplish this?

推荐答案

一个巧妙的小技巧

如果 <section> 元素是 <main>. 如果那里有任何其他元素,这将不起作用.在您的情况下,它应该像这样工作(http://jsfiddle.net/Ljm323qb/2/):

section {
     max-width: 500px;
}
/* The STAR of the show */
section:only-child {
     max-width: 1000px;
}

如本 Codepen 所示:http://codepen.io/omarjuvera/pen/ByXGyK?editors=110

As illustrated in this codepen: http://codepen.io/omarjuvera/pen/ByXGyK?editors=110

+ 选择器会选择紧跟在元素之后的兄弟(https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors)

There's the + selector which would select a sibling that comes right after the element (https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors)

还有 ~ 选择器,它选择所有以下兄弟姐妹(https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors)

And there's the ~ selector which selects all following siblings (https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors)

您可以通过将 <aside> 元素放在 <section> 元素之前并使用同级选择器来实现.

You could achieve it by putting the <aside> element before the <section> element and using a sibling selector.

这是一个例子:http://jsfiddle.net/Ljm323qb/1/

未来概览
很快这将成为可能,使用一个新的 :has 伪类 (http://dev.w3.org/csswg/selectors-4/#relational)
您将能够调用类似 main:has(>side) >{ ... } 部分,但不幸的是,我们将不得不等待 :(

A quick look in the future
Soon this will be possible, with a new :has pseudo class (http://dev.w3.org/csswg/selectors-4/#relational)
You'll be able to call something like main:has(> aside) > section { ... } but we'll have to wait for that, unfortunately :(

相关文章