Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
762 views
in Technique[技术] by (71.8m points)

sass - How to compose multiple classes into a single semantically-named class?

I've been reading up on Block-Element-Modifier naming conventions, semantically-named style rules, etc. and I'd like to replace multiple class names in my html with a single, semantic class name. Can't seem to make it happen, though. Example:

I'd like to replace my Bootstrap navbar

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">

with

<nav class="header__navbar" role="navigation">

I know I could use jQuery to do this procedurally, but I'd prefer not to. I've tried several approaches using variable names, #{} interpolation syntax, mixins, and @extend, etc. but just get syntax errors or invalid results.

Is this just not something Sass was designed to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is this just not something Sass was designed to do?

Sass does support this use case.

What you need is extending.

  1. Have navbar, navbar-default and navbar-fixed-top classes defined as you would with a non-semantic approach:

     .navbar { display: table; }
     .navbar-default { background-color: deeppink; }
     .navbar-fixed-top { position: fixed; top: 0; left: 0; width: 100%; }
    
  2. Below, extend your header__navbar class with those:

    .header__navbar {
      @extend .navbar;
      @extend .navbar-default;
      @extend .navbar-fixed-top;
    }
    
  3. Once you get rid of non-semantic classes in your HTML markup completely, you no longer need them in your CSS. So turn them into placeholder selectors aka silent selectors. To do so, replace the . with % both in the rules where they are defined and in @extend directives that use them. E. g.:

     %navbar { display: table; }
     %navbar-default { background-color: deeppink; }
     %navbar-fixed-top { position: fixed; top: 0; left: 0; width: 100%; }
    
    .header__navbar {
      @extend %navbar;
      @extend %navbar-default;
      @extend %navbar-fixed-top;
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...