SMACSS


Posted by TempuraEngineer on 2022-04-20

SMACSS是甚麼

SMACSS(Scalable and Modular Architecture for CSS)是一種CSS的設計模式。它可以讓你的css更彈性更語意化

大致可以分為5個概念

  1. Base:每一頁都會出現的通用樣式

    defaults values like the padding, margin, font and other properties, this values are used on the entire web site and all elements.

  2. Layout:nav、footer等等在多個頁面會出現的東西。grid系統也歸在這

    Layouts hold one or more modules together.
    <>
    developers show layout elements by prefixing the class with l-, e.g. l-header, l-footer

  3. Module:獨立的CSS組件

    the reusable, modular parts of our design like navbar, sidebar and some elements that are repeated in the site.

    a. sub-module(子模組)
    css覆寫(override)之意

    bootstrap_nav-link

     /* 擷取bootstrap.css,然後小改 */
     .nav-link {
       display: block;
       padding: 0.5rem 1rem;
     }
    
     .nav-tabs .nav-link { /* 使用後代選取器 */
       padding: 0.25rem 0.5rem; /* 覆寫 */
       margin-bottom: -1px;
       border: 1px solid transparent;
       border-top-left-radius: 0.25rem;
       border-top-right-radius: 0.25rem;
     }
    
     .nav-link:hover {
       text-decoration: none;
     }
    
     .nav-tabs .nav-link:hover {
       border-color: #e9ecef #e9ecef #dee2e6;
     }
    
  4. State:描述module或layout狀態的形容詞。常用於class,可配合JS做樣式切換

    e.g. active, inactive, expanded, hidden. These are prefixed with is-, e.g. is-active, is-inactive, is-expanded, is-hidden.

    There is plenty of similarity between a sub-module style and a state style. They both modify the existing look of an element. However, they differ in two key ways: 1.State styles can apply to layout and/or module styles; and 2.State styles indicate a JavaScript dependency

    <script>
       const links = Array.apply(null, document.querySelectorAll('.nav-link'));
    
       links.addEventListener('click', (e) => {
           forEach(ele => {
               ele.classList.remove('active');
           })
           e.target.classList.toggle('active');      
       )
    </script>
    
    <style>
     .nav-tabs .nav-link.active {
       color: #495057;
       background-color: #fff;
       border-color: #dee2e6 #dee2e6 #fff;
     }
    </style>
    
  1. Theme:全域設定

    It is used to contain the rules of the primary colors, shapes, borders, shadows, and such.
    Mostly these are elements which repeat across a whole website.


SMACSS重點摘要

  1. 彈性
    不綁定HTML tag、id
    避免用後代選取器,但是情況還是可以用(像.nav-link的例子)

  2. 語意化,有助於SEO
    一看就知道class用途

    d-block、d-none、d-flex
    button-danger、button-success、button-outline
    item-active、item-disable


📖

What is SMACSS
What is SMACSS?
Sass教學 (29) - SMACSS - Module Rules
Sass教學 (30) - SMACSS - State Rules


#SMACSS







Related Posts

WEB 網路基礎概念

WEB 網路基礎概念

[Note] webpack5 problem: Environment Variable (.env)

[Note] webpack5 problem: Environment Variable (.env)

MTR04_0707

MTR04_0707


Comments