CSS class naming convention

前端 未结 4 552
梦如初夏
梦如初夏 2020-11-30 21:20

On a web page, there are two blocks of controls (primary and secondary), what class names would most people use?

Choice 1:

4条回答
  •  离开以前
    2020-11-30 21:37

    The direct answer to the question is right below this one, by Curt.

    If you're interested in CSS class naming conventions I suggest to consider one very useful convention named BEM (Block, Element, Modifier).

    UPDATE

    Please read more about it here - http://getbem.com/naming/ - that's a newer version that renders the following answer obsolete.


    Main principles:

    • A page is constructed from independent Blocks. Block is an HTML element which class name has a "b-" prefix, such as "b-page" or "b-login-block" or "b-controls".

    • All CSS selectors are based on blocks. There shouldn't be any selectors that aren't started with "b-".

    Good:

    .b-controls .super-control { ... }
    

    Bad:

    .super-control { ... }
    
    • If you need another block (on the another page maybe) that is similar to block you already have, you should add a modifier to your block instead of creating a new one.


    Example:

    With modifier:

    Then you can specify any modifications in CSS:

    .b-controls { font: 14px Tahoma; }
    .b-controls .super-control { width: 100px; }
    
    /* Modified block */
    .b-controls.mega { font: 20px Supermegafont; }
    .b-controls.mega .super-control { width: 300px; }
    

    If you have any questions I'd be pleased to discuss it with you. I've been using BEM for two years and I claim that this is the best convention I've ever met.

提交回复
热议问题