An example of using CSS methodologies to achieve modularity

An example of using CSS methodologies to achieve modularity

1. What are CSS methodologies?

CSS methodologies can be understood as design patterns or CSS specifications. The market usage is as follows:

Source of the above image: https://2019.stateofcss.com/technologies/

You may not take the time to pay attention to and understand CSS methodologies in your daily development, but as you gain experience, you may think for yourself, or read other people’s code, and refer to mature frameworks on the Internet, which more or less contain some shining points of CSS methodologies. The following mainstream CSS methodologies can help you summarize and sort out the content.

2. Common CSS methodologies

1. OOCSS

面向對象的CSS OOCSS for short) was proposed by Nicole Sullivan in 2008 based on her work at Yahoo.

(1) Rules

1. Don’t use ID, use Class

Directly use classes to set styles. This not only increases semantics, but also reduces CSS's dependence on HTML.

2. Separation of structure and style

Although early HTML and CSS achieved the separation of structure and style, there are still two types of styles in CSS:

  • Structural style (e.g. length, width, distance)
  • Skin style (e.g. color, shading)

So OOCSS recommends separating these two styles.

For example, there are three buttons, white/green/red, which can be defined as:

class="btn btn-default"

class="btn btn-green"

class="btn btn-red"

If you really have a lot of purple buttons, you can create a separate purple button class. This can greatly reduce the amount of CSS code.

3. Separation of container and content

Content should never be confined to a specific container and should be freed for reuse.

# Wrong way to write.header.action {
}
.header .action .login {
}
.header .action .register {
}

# Correct way to write .header{
}
.action{
}
.login {
}
.register {
}

Inherited selectors are useful because they can reduce style conflicts caused by the same name (often occurring when multiple people are collaborating on a project). However, we should not overuse it.

(2) Advantages and Disadvantages

benefit:

  • Modular and reusable
  • Reduce code duplication
  • Improve scalability, maintainability, and readability

shortcoming:

  • Although it reduces the number of deeply nested selectors, it adds more classes
  • If there aren’t a lot of repeated visual patterns in your code, such as in a small project, applying OOCSS may not be practical.

(3) Examples

Bootstrap uses OOCSS.

For example:

html

 <div class='header'>
        <ul class='menu'> 
            <li class='menu-item active'>1</li>
            <li class='menu-item'>2</li>
            <li class='menu-item'>3</li>
        </ul>
        <div class="action">
            <button class="btn btn-login">login</button>
            <button class="btn btn-register">register</button>
        </div>
    </div>

CSS:

.header {
}
.menu {
}
.menu-item {
}
.item.active {
}
.action {
}
.btn {
}
.btn-login {
}
.btn-register{
}

2. BEM

BEM - Block Element Modfier. Born in 2009.

(1) Content

BEM consists of three parts:

  • Block - block, such as header
  • Element - child element, such as item under block menu
  • Modfier - state, such as .current, .active

(2) Rules

1. Naming conventions

  • - : It is used only as a hyphen to indicate the connection between multiple words in a block or a sub-element.
  • __ underscores: used to connect blocks and their subelements.
  • -- hyphen: used to describe a state of a block or a sub-element of a block.

In the standards of some companies (such as Tencent), double hyphens are replaced by single underscores ( _ ).

For example: .block-name__element--modifier

demo-html:

    <div class='header'>
        <ul class='header__menu'> 
            <li class='header__menu-item--active'>1</li>
            <li class='header__menu-item'>2</li>
            <li class='header__menu-item'>3</li>
        </ul>
        <div class="header__action">
            <button class="header__btn--login">login</button>
            <button class="header__btn--register">register</button>
        </div>
    </div>

demo-less:

.header {
    &__menu {}
    &__menu-item {}
    &__action {}
    &__btn {  
        &--login {}
        &--register {}
    }    
}

2. Avoid nesting

BEM has at most three levels: B+E+M.

So please avoid the format of .block__el1__el2 and change it directly to .block_el2 .

The block here is very similar to a namespace.

(3) Advantages and disadvantages

benefit:

  • The hierarchical relationship is clear at a glance and readable
  • There is no need to rely on hierarchical selectors to limit the scope of constraints, which can avoid cross-component style pollution.

shortcoming:

  • The naming method is long and ugly, and inconvenient to write (you can use less/sass to simplify the writing)
  • In smaller components, the BEM format may seem useless. However, for public, global module style definitions, it is recommended to use the BEM format. (Especially public components released to the public)

other:

BEM naming will make the class name longer, but after gzip compression, the bandwidth overhead can be ignored.

BEM does not allow the use of tag selectors. Even the simplest li must be written as .menu-item.

(4) Practice

Ele.me's framework elementUI is a type of BEM, or you can also study the website company.yandex.ru/.

3. SMACSS

SMACSS (Scalable & Modular Architecture CSS, which means the scalability and modular architecture of CSS). Jonathan Snook came up with it in 2011 while he was working at Yahoo, writing CSS for Yahoo Mail.

(1) Rules

1. Categorizing CSS Rules

It divides CSS into 5 different categories:

Base Basic Specifications

For example, CSS Reset and CSS Normalize.

Layout layout specifications

For example, left and right columns, and grid systems.

Module

For example, a product list, a navigation bar. Reusable.

State Specification

For example, the selected state.

Theme style specifications

2. Naming Rules

Add前綴to the class name:

Base does not require a prefix. And use tags instead of classes and IDs.

  • l- is used as a prefix for Layout: l-inline
  • m- is used as a prefix for Module: m-callout . But you don't have to use a prefix.
  • is- is used as a prefix for State: is-collapsed
  • Theme usually creates a new theme.css, using the previously existing class names. If you want to use a separate class name, you can use theme- prefix.

example:

<div class="l-box m-profile m-profile--is-pro-user">
  <img class="m-avatar m-profile__image" />
  <p class="m-profile__bio">...</p>
</div>

(2) Examples

Online demo: https://codepen.io/savemuse/pen/gWVpvd

4. Atomic CSS

Atomic CSS was also proposed by Yahoo, and can be understood literally as原子CSS .

(1) Example

<div className="P(10px) M(20%) Pos(f) Start(50%) Bgc(#fff)" />

There will be a special Atomic CSS tool to help parse the class name in the above HTML into normal CSS. (slightly)

(2) Advantages and Disadvantages

Benefits: Minimize CSS styles into components and maximize reusability.

Disadvantage: This is basically writing inline-style, but we use class name to express it.

(3) Summary

This approach is really radical. I can't accept it for now.

Conclusion

Leaving aside the radical Atomic, I have the following suggestions for the remaining OOCSS/BEM/SMACSS:

Their respective ideas are complementary and conflicting, and they can be used in a trade-off manner in actual development.

They can all be combined with CSS preprocessors (such as less/sass) for better efficiency

By comparing and summarizing the benefits introduced above, we find that the core problem they solve is: modularity

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

<<:  Building FastDFS file system in Docker (multi-image tutorial)

>>:  14 Ways to Create Website Content That Engages Your Visitors

Recommend

Detailed explanation of NodeJS modularity

Table of contents 1. Introduction 2. Main text 2....

HTML table tag tutorial (27): cell background image attribute BACKGROUND

We can set a background image for the cell, and w...

MYSQL METADATA LOCK (MDL LOCK) MDL lock problem analysis

1. Introduction MDL lock in MYSQL has always been...

Methods and steps for deploying multiple war packages in Tomcat

1 Background JDK1.8-u181 and Tomcat8.5.53 were in...

mysql implements the operation of setting multiple primary keys

User table, ID number must be unique, mobile phon...

HTML Basics: HTML Content Details

Let's start with the body: When viewing a web ...

Json string + Cookie + localstorage in JS

Table of contents 1.Json string 1.1Json Syntax 1....

The difference between html empty link href="#" and href="javascript:void(0)"

# contains a location information. The default anc...

Summary of Linux command methods to view used commands

There are many commands used in the system, so ho...

Use of Docker UI, a Docker visualization management tool

1. Introduction to DockerUI DockerUI is based on ...

Solve the error problem caused by modifying mysql data_dir

Today, I set up a newly purchased Alibaba Cloud E...

Vue3 encapsulates the side navigation text skeleton effect component

Vue3 project encapsulation side navigation text s...

js to implement web calculator

How to make a simple web calculator using HTML, C...

In-depth analysis of Flex layout in CSS3

The Flexbox layout module aims to provide a more ...