【问题标题】:Css with regex for id带有正则表达式的 css 为 id
【发布时间】:2019-06-12 22:34:27
【问题描述】:

我只希望第一个和第三个id 是红色的。这怎么可能?

HTML 和 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>

【问题讨论】:

  • CSS 中没有复杂的正则表达式。

标签: css


【解决方案1】:

您可以为此使用特殊的 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>

【讨论】:

  • 令人惊讶的是它的工作原理,你有这个 w3c 规范的链接吗?
  • 非常感谢,它有效。没想到我可以加入两个这样的正则表达式。
  • 如果有这个支持矩阵也可以用于两个选择器的组合kimblim.dk/css-tests/selectors 会很有趣
  • 我在 div 之前添加了#,就像我对一个不起作用的“id”所做的那样。最初有点混乱,但它奏效了
【解决方案2】:

您可以使用以下事实:这些元素的 ID 以 s 开头,使用属性选择器 ([id^="s"]) 并以 0 结尾,使用属性选择器 ([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

【讨论】:

  • 谢谢,您的解决方案有效,类似于上面的 Pawel。
【解决方案3】:

这不是 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>

只有具有该特定类别的人才会受到影响。

【讨论】:

    【解决方案4】:

    或者你可以使用伪选择器:

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

    IE8 或更低版本不支持,但在其他地方应该没问题。

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多