CSS多选用方括号

时间:2014-11-18 07:58:54

标签: css

我的网站上有这段代码:

#stage-1-picture,
#stage-2-picture,
#stage-3-picture,
#stage-5-picture {
    margin-top: 20px;
    position: relative;
    z-index: 1;
}

我一直想知道是否有办法用方括号缩短这个多项选择,以便我可以使用某种plceholder来代替数字1,2,3,4,5。

谢谢!

3 个答案:

答案 0 :(得分:2)

不是真的,而不是诉诸某种穷人的正则表达式选择器。但是,可以使用一些CSS3 attribute selectors:来完成

p[id^="item-"][id$="-test"] { color: red; }
<p id="item-1-test">Test 1 (should be red)</p>
<p id="item-1-test">Test 2 (should be red)</p>
<p id="item-1">Without last part (should not be red)</p>
<p id="1-test">Without first part (should not be red)</p>
<p id="different">Totally different (should not be red)</p>
<p id="item--test">Warning! Incorrectly red.</p>

CSS规则仅选择以“item-”开头并以“-test”结尾的元素。

但是,我建议您查看不同的方法,无论是SASS,jQuery,还是完全改变您的策略:您的元素似乎需要class="stage-picture" ...

答案 1 :(得分:1)

Suresh告诉你,你需要和sass一起去。 sass的解决方案是:

%temp {
  margin-top: 20px;
  position: relative;
  z-index: 1;
}

@for $i from 1 through 5 {

  #stage-#{$i}-picture {
    @extend %temp;
  }
}

示例:http://sassmeister.com/gist/904fb5c267e5ddfe0c8a

答案 2 :(得分:0)

你可能会使用像SASS或LESS这样的预处理器。然而,为您的任务使用类更自然,因为这正是您所需要的:具有类似特征的目标元素集:

.stage-picture {
    margin-top: 20px;
    position: relative;
    z-index: 1;
}

HTML:

<div class="stage-picture" id="stage-1-picture"></div>
<div class="stage-picture" id="stage-2-picture"></div>
<!-- etc ... -->