用于在元素ID中搜索数字的CSS3选择器

时间:2012-03-26 00:36:22

标签: css css3 css-selectors

我想将自定义CSS属性提供给id中由数字标识的元素的指定范围。

HTML:

<div id="game">
  <div id="game-board-field-1-street-name"></div>
  <div id="game-board-field-2-street-name"></div>
  <div id="game-board-field-3-street-name"></div>
  <div id="game-board-field-4-street-name"></div>
  ...
  <div id="game-board-field-11-street-name"></div>
  <div id="game-board-field-12-street-name"></div>
  <div id="game-board-field-13-street-name"></div>
  <div id="game-board-field-14-street-name"></div>
  ... too many ...
</div>

CSS:

#game div[id$=street-name] { /* I want this selector to get applied only to streets 1-4 */
  font-size: 10px;
}

#game div[id$=street-name] { /* This one to streets 11-14 */
  font-size: 14px;
}

有没有办法只用CSS来处理它?<​​/ p>

1 个答案:

答案 0 :(得分:4)

您不能直接按编号ID选择,因为CSS不提供动态属性选择器。

但是,如果您的结构使得每个编号为div的{​​{1}}对应于#game父元素中的位置,则您可以使用:nth-child()代替:

/* First 4 elements */
#game div:nth-child(-n+4) {
  font-size: 10px;
}

/* Elements starting from the 11th and ending at the 14th */
#game div:nth-child(n+11):nth-child(-n+14) {
  font-size: 10px;
}