2017-02-27 77 views
0

我只想要第一個和第三個ID是紅色的。那可能嗎? Css與正則表達式的編號

#sections div[id^='s.*0'] { 
 
    color: red; 
 
}
<div id="sections"> 
 
<div id="s10">one</div> 
 
<div id="s2">two</div> 
 
<div id="s30">three</div> 
 
<div id="t1">four</div> 
 
</div>

+2

在CSS中沒有複雜的正則表達式。 – pol

回答

6

您可以使用特殊的CSS選擇器:id$='0'表示ID以0結尾,id^='s'表示ID以s開頭。

#sections div[id$='0'][id^='s'] { 
 
    color: red; 
 
}
<div id="sections"> 
 
<div id="s10">one</div> 
 
<div id="s2">two</div> 
 
<div id="s30">three</div> 
 
<div id="t1">four</div> 
 
</div>

+0

驚人的是它的工作原理,你有一個鏈接到這個w3c規範? – abimelex

+1

https://developer.mozilla.org/pl/docs/Web/CSS/Attribute_selectors –

+0

非常感謝,它的工作原理。不會猜到我可以加入這樣的兩個正則表達式。 – stumped

0

這不是什麼ID爲設計做的,CSS不支持正則表達式。但是,您的解決方案是使用類。

#sections .s-class { 
    color: red; 
} 
<div id="sections"> 
    <div id="s10" class='s-class'>one</div> 
    <div id="s2" class='s-class'>two</div> 
    <div id="s30" class='s-class'>three</div> 
    <div id="t1">four</div> 
</div> 

只有那些具有該特定類的人才會受到影響。

1

你可以使用一個事實,即那些元件具有使用開始屬性選擇器([id^="s"])與s開始,並且使用具有屬性選擇器的端部與0結束的ID([id$="0"]) :

#sections div[id^="s"][id$="0"] { 
 
    color: red; 
 
}
<div id="sections"> 
 
<div id="s10">one</div> 
 
<div id="s2">two</div> 
 
<div id="s30">three</div> 
 
<div id="t1">four</div> 
 
</div>

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

+0

謝謝你,你的解決方案工作,類似於上面的Pawel。 – stumped

0

或者你可以使用一個僞選擇:

#sections:nth-child(1), #sections:nth-child(3) { 
    color:red; 
} 

它不是在IE8或更低的支持,但應該罰款別處。