在我的 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> 样式.<section> ONLY if <aside> is present.如果 <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 :(
这篇关于CSS:仅当存在较晚的兄弟时才选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
:target 为空时的 CSS 选择器CSS selector when :target empty(:target 为空时的 CSS 选择器)
CSS 直接后代 (>) 在选择性方面没有任何价值Does the CSS direct decendant (gt;) not have any value in selectivity?(CSS 直接后代 (gt;) 在选择性方面没有任何价值吗?)
使用 querySelectorAll().方法返回的结果是否有序?Using querySelectorAll(). Is the result returned by the method ordered?(使用 querySelectorAll().方法返回的结果是否有序?)
Safari 错误:当使用 JS 删除项目时,first-child 不更Safari bug :first-child doesn#39;t update display:block when items are removed with JS(Safari 错误:当使用 JS 删除项目时,first-child 不更新
nth-子 CSS 选择器nth-Child CSS selectors(nth-子 CSS 选择器)
对多个 HTML 标签使用相同的 ID?Using same ID for multiple HTML tags?(对多个 HTML 标签使用相同的 ID?)