Coda Chang Coda Chang - 1 month ago 21
CSS Question

Sass selector combine attribute

I want to use

font-family: 'Noto Sans TC'
in specific language, so I wrote the following code in
.scss
.

body{
&[lang="en"]{ font-family: 'Noto Sans TC', sans-serif; }
&[lang="zh-TW"]{ font-family: 'Noto Sans TC', sans-serif; }
&[lang="zh-CN"]{ font-family: 'Noto Sans SC', sans-serif; }
}


Then in html

$(document).ready(function() {
$('body').attr('lang', translationManager.getCurrentLanguage());
});


It works fine, but I was wondering is there a better way to write the
.scss
code?

Answer

SASS is a powerful CSS tool to make use of in programming. It provides a lot of programming logics support like if/else, each, for loop, etc., so in your situation it's better to make use of @each functions in SASS-

$langs: 'en','zh-TW','zh-CN'; // Define the array for your languages

@each $lang in $langs{
  body{
     &[lang="#{$lang}"]{
        font-family: 'Noto Sans TC', sans-serif;
     }
  }
}

this will result in something like this-

body[lang="en"] {
  font-family: 'Noto Sans TC', sans-serif;
}

body[lang="zh-TW"] {
  font-family: 'Noto Sans TC', sans-serif;
}

body[lang="zh-CN"] {
  font-family: 'Noto Sans TC', sans-serif;
}

You can check this here - http://www.sassmeister.com/,

Also it depends what kind of compiler tool you're using, for ex. if you're using gulp and it's gulp-sass package it'll minimize the code and write it in a comma-seperated way.

For more experiments and advance features refer the below links-

http://thesassway.com/intermediate/if-for-each-while

https://www.sitepoint.com/sass-maps-vs-nested-lists/

https://css-tricks.com/the-sass-ampersand/