問題描述
在我的 HTML 結(jié)構(gòu)中,我是這樣設(shè)置的:
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;
僅當(dāng) <aside>
存在.默認(rèn)為 section { max-width: 1000px;}
(當(dāng) <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)
不同于 一個標(biāo)簽的選擇器,后跟另一個標(biāo)簽;用戶 [提出問題] 想要始終設(shè)置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")
- 僅當(dāng)
<aside>
存在時,我才需要設(shè)置<section>
樣式. - 我無法更改 HTML 的順序 >_<
- 只能用 CSS 完成嗎?
- 我需要什么選擇器或如何設(shè)置它?
- 如果不能用 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>
是否達(dá)到您想要的效果>. 如果那里有任何其他元素,這將不起作用.在您的情況下,它應(yīng)該像這樣工作(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>
元素之前并使用同級選擇器來實現(xiàn).
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)
您將能夠調(diào)用類似 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 :(
這篇關(guān)于CSS:僅當(dāng)存在較晚的兄弟時才選擇元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!