郭泇吟
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # BEM CSS 的認識與了解 ###### tags: `CSS` [TOC] --- ## 什麼是 BEM BEM 是 `Block` `Element` `Modifier` 的縮寫,一種「**前端命名規範**」,為了讓 CSS Class 更好維護的命名方式,將用戶界面劃分為各種獨立的**模塊(Block)**,藉由不同組件的命名讓程式碼易懂、可重用,進而有效率地開發和維護。 - 優點:具獨立性與複用性 - 缺點:命名長度過長。 由Yandex 公司推出的,包括了規範以及其配套構建工具。如今提到的 BEM 主要是指其中的規範,在 BEM 最新的推廣頁中,對其的描述為: > BEM 是一種命名方法,能夠幫助你在前端開發中實現可複用的組件和代碼共享。 官方網址: http://getbem.com/ ## 一、BEM 組成介紹 ### 1. Block >![](https://i.imgur.com/LwiDMYv.png) >圖片來源:https://en.bem.info/methodology/key-concepts/ **Block** 意為網頁畫面中看到的多個不同的區塊,例如:選單、搜尋......等,其特性有: - 具有獨立性:可在開發中重複利用,降低程式碼的複寫率,提升開發速度。 - 使用彈性高:可以放在頁面上任一位置,也可以互相嵌入。 #### 1-1. 選擇器的特色和命名 - Block name 描述他的功能、區塊的目的,而非狀態。 ```css header, container, menu, checkbox, input ``` - 不會添加樣式在裡面(例如:color, margin......等)。 - 使用BEM的同時,不會使用 CSS 標籤選擇器和 ID 選擇器。 - 命名方式:為單一單字`block`或使用1個破折號來連接過長的單字`block-name`。 #### 1-2. 嵌入 - Block 和 Block 之間可以彼此嵌入。 - 可以有任意級別的嵌入層次。 ```htmlmixed= <!-- `header` block --> <header class="header"> <!-- 嵌套 `logo` block --> <div class="logo"></div> <!-- 嵌套 `search-form` block --> <form class="search-form"></form> </header> ``` ### 2. Element >![](https://i.imgur.com/TQDOGw2.png) > 圖片來源:https://en.bem.info/methodology/key-concepts/ **Element** 是 Block 中的组成成分。Element 不能脫離 Block 單獨使用。 - Element 是 Block 中的组成成分。 - Element 不能脫離 Block 單獨使用;但 Block 可以沒有 Element。 #### 2-1. 選擇器的特色和命名 - Element name 如同 Block name 描述的是目的而非狀態。 - 命名的完整結構是`block-name__element-name`。 - 命名方式:使用2個下底線`__`與 Block name 名稱分隔。 ### 3. Modifier >![](https://i.imgur.com/yziJLXZ.png) >圖片來源:https://en.bem.info/methodology/key-concepts/ **Modifier name** 定義了 Block 或 Element 的外觀,狀態或行為的實體。 - 外觀:例如尺寸或主題`size-xl`, `theme-light`。 - 狀態:與通常狀態有什麼不同,`disabled`, `focused`。 - 行為:對該元素產生什麼影響,`right-bottom`。 #### 3-1. 選擇器的特色和命名 - 同一個 Block name 或 Element name 可以允許多組 Modifier name。 - 命名方式:2個破摺號`--`與 Block name 或 Element name 分隔`block-name__element--modifier`。 - 原本的命名方式為1個底線 `_`,但因為閱讀性低而改良為現在的方式。 ## 二、Mix 混搭使用 結合多個 BEM 實體的行為和樣式,就不需要重複的程式碼,如同積木般可以有不同的排列組合,每一次重新組合都是一種創新與發現。 ```htmlmixed= <!-- `header` block --> <div class="header"> <!-- block:`search-form`混合在 block:`header`內的 element:`search-form` --> <div class="search-form header__search-form"></div> </div> ``` 在上述的範例中,結合 block`search-form`和 Element`header__search-form`。 如此一來,便可允許我們在 Element:`header__search-form`中設置額外的形狀和定位。而 `search-form` 本身並無受到影響,因此我們還是可以在其他頁面位置使用該 Block。這就展現 BEM 的核心邏輯─「獨立性與複用性」。 在傳統命名方式中,我们經常使用套的方式為 `.header .search-form` 對局部樣式進行調整,但這樣做會改變選擇器的權重。而在 BEM 的思維,保持選擇器並列和低權重是必須遵守的準則。 ## 三、文件撰寫 也可依 BEM 中採用的組件方式來撰寫文件。 * 一個單獨的 Block 對應 一個單獨的目錄。 * Element 目錄的名稱以2個底線 `__` 開始。 * Modifier 目錄的名稱以2個破折號 `--` 開始。 * Element 和 Modifier 的同樣可各自擁有不同的文件。 ``` search-form/ __input/ search-form__input.css search-form__input.js __button/ search-form__button.css search-form__button.js --theme/ search-form_theme_islands.css search-form block search-form_theme_lite.css search-form.css search-form.js ``` 我們不一定要遵循 BEM 建議的文件架構,也可以使用任何可替代的架構,只要根據 BEM 原則來組織我們的文件結構,以下有另外兩種架構方式供參考: - Flat:https://en.bem.info/methodology/filestructure/#flat - Flex:https://en.bem.info/methodology/filestructure/#flex ## 四、例外命名情況 並非所有的 CSS 命名方式都要如此,當某些 CSS 設定可重複使用時,就可以獨立出來,讓該設定被重複使用。例如: ``` .clearfix{ clear:both } .caps { text-transform: uppercase; } ``` > 這條 CSS 不屬於任何一個 BEM 範疇,它僅僅只是一條單獨的樣式。 ## 結論 **一、命名方式整理:** * Block:block 或 block-name * __Element:__element 或 __element-name * --Modifier:--modifier 或 --modifier-name 整體結構:`block-name__element-name--modifier-name` **二、與 OOCSS 不同的是:** - BEM 是一種命名規範。 - OOCSS是CSS的設計思想。事實上 BEM 也用到了 OOCSS 的思想。 **三、** 在許多情境下,命名方式都不是絕對的,依照不同的情況來做彈性的調正,而非墨守成規。近幾年前端框架 Boostarp, Tailwind 流行起來,大多數人較習慣 OOCSS 的命名方式,筆者也是一樣的,但還是有人在寫 BEM。 而無論是 BEM, OOCSS 的發明,都可以幫助 CSS 的開發與管理,加速了解專案的架構與增加閱讀性,如此一來便協助了工程師在開發上更有效率! ## 參考資料 [BEM 規範思維 – 讓 CSS 更利於開發與維護](https://www.astralweb.com.tw/apply-bem-to-css-coding-and-maintenance-2/) [淺談 BEM CSS - CSS 設計模式與架構](https://w3c.hexschool.com/blog/35afa83f)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully