Sass looping through class names starting with number

倖福魔咒の 提交于 2019-12-01 12:33:20

HTML5 is fine with starting ID's and class names with digits these days, but CSS isn't (Here's some info about all this).

Sass probably wouldn't allow you to create invalid CSS selector, such as .22ltr-porche so that makes sense. Though there are ways to get around it.

You could try this:

@each $car in
  bmwwhite
  hondared
  22ltr-porche
  30ltr-cossworth
 {
  [class="#{$car}"] {
    background:url(/img/cars/#{$car}.jpg) no-repeat 
  }
 }

That will create a selector that looks like this [class="22ltr-porche"] and Sass is OK with that.

Unqualified attribute selectors like this tends to be very slow though. You should try to combine the attribute selector with something with more specificity. Here's an example plunkr.

The class you're trying to generate is invalid. Running it through the validator will give this error:

In CSS1, a class name could start with a digit (".55ft"), unless it was a dimension (".55in"). In CSS2, such classes are parsed as unknown dimensions (to allow for future additions of new units) To make "22ltr-porche" a valid class, CSS2 requires the first digit to be escaped ".\32 2ltr-porche" [22ltr-porche]

So, we need to escape the leading number like it says:

@function escape_leading_numbers($s) {
  $first-char: str_slice(#{$s}, 0, 1);
  $found: index('1' '2' '3' '4' '5' '6' '7' '8' '9' '0', $first-char);
  @return if($found, unquote(str-insert(str-slice(#{$s}, 2), "\\3#{$first-char} ", 1)), $s);
}

$name: '007';

.#{escape_leading_numbers($name)} {
  color: red;
}

@each $car in
  bmwwhite
  hondared
  22ltr-porche
  30ltr-cossworth
 {
  .#{escape_leading_numbers($car)} {
    background:url(/img/cars/#{$car}.jpg) no-repeat
  }
 }

Output:

.bmwwhite {
  background: url(/img/cars/bmwwhite.jpg) no-repeat;
}

.hondared {
  background: url(/img/cars/hondared.jpg) no-repeat;
}

.\32 2ltr-porche {
  background: url(/img/cars/22ltr-porche.jpg) no-repeat;
}

.\33 0ltr-cossworth {
  background: url(/img/cars/30ltr-cossworth.jpg) no-repeat;
}

http://sassmeister.com/gist/e07d3fd4f67452412ad0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!