且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-20 23:16:03

一个巧妙的小技巧

如果 <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 :(