Sass looping through class names starting with number

こ雲淡風輕ζ 提交于 2019-12-09 03:25:51

问题


I am looping through a list of names in sass and it seems that the sass is breaking when it arrives at a point where the class names starts with a number. Infact when i commented out the class names starting with a numeric value, the sass compilation worked fine. That said i cannot rename the class names. How I can make it work? Below is the code im trying:

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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/30137176/sass-looping-through-class-names-starting-with-number

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