Background: When we work on large projects or team development, we often find that our code is messy, hard to read, and hard to expand. Especially when we look back at our code after a while, we have to remember how we thought when we wrote it. As a result, people try to be consistent in their code style. However, the biggest difficulty is that fixing a minor problem can create more ugly hacks, or a minor CSS change can affect JavaScript functionality. But these problems can be largely avoided if we plan them carefully at the beginning of our project. Today we will discuss how to write a good CSS code
What does a good CSS look like
- Keep style sheets maintainable
- Keep code readable
- Keep your stylesheets extensible
To maintain good CSS code, you first need to have a consistent CSS team specification, and that starts with the CSS architecture.
CSS architecture
The CSS has the following five design architectures
1. OOCSS
Object-oriented CSS,
- Structure and topic separation – Reduce dependence on HTML structure
- Theme and theme separation – increases the reusability of styles
Based on OOCSS, another design pattern emerges
2. BEM
It can also be thought of as a naming convention that essentially makes the page structure clear
Block, Element__, Modifier
There are several rules
- Block elements should be dominated by attributes of the element itself
- Element focuses on Element position and shape
- Modifier modifies the current state and subject
- An Element must be inside the Block, not outside it
- Modifier is more about the shape and state of the current component
It is evident that
- The structure is clear
- Position quickly
- Function is clear
In the context of componentized scenarios, blocks represent logically and functionally independent page components. Element encapsulates behavior (JavaScript), templates, styles (CSS), and other implementation technologies.
For example
<header class="header">
<img class="logo">
<form class="search-form">
<input class="input">
<button class="button"></button>
</form>
<ul class="lang-switcher">
<li class="lang-switcher__item">
<a class="lang-switcher__link" href="url">en</a>
</li>
<li class="lang-switcher__item">
<a class="lang-switcher__link--active" href="url">ru</a>
</li>
</ul>
</header>
Copy the code
block-name__element-name--modifier-name--modifier-value
React uses the same naming scheme
BEMnaming tool, providing detection of BEMnaming
However, in the face of large projects, the clutter of CSS makes it difficult for developers to look for reusable code in the vast number of code
3. SMACSS
(What ‘s Smacss) [smacss.com/]
There are three main specifications for the design:
- Categorizing CSS Rules
- Naming Rules
- Minimizing the Depth of Applicability
To achieve a clear CSS structure, the CSS is divided into
- Base-global styles, such as global-reset and normalize.css
- Layout – Layout of pages, such as the grid
- Module – Component layout
- State – State of an element, such as visible and hidden
- Theme or Skin – More configuration styles for specific themes
- JavaScript hooks
In particular, JavaScript is recommended to decouple styles
<button class="btn btn--buy js-buy-now"></button>
Copy the code
There are some differences in naming conventions
.layout-header
.is-hidden
.theme-nav
Copy the code
Minimize the depth of adaptation to reduce the coupling degree between HTML and CSS and avoid the impact of HTML changes on CSS
.sidebar ul h3 {}
.side {}
Copy the code
4. ITCSS
The CSS is layered in more detail
Base is divided into Settings, Tools, Generic, and Base. Objects, Components, and Trumps correspond to Layout, Module, (State, Theme). The advantage of this design is that it makes the code even more reusable
5. ACSS
One style attribute one class, which is typified by TailwindCSS, has the disadvantage of breaking semantics
.block{ display: block; }
.hidden { display: none; }
.p-2 { padding: 0.75 rem; }
.flex { display: flex; }
.text-base { font-size: 1rem; }
.bg-green-200 { background-color: # 123456 }
<div className="m-2 p-2 text-2xl text-gray-500">I am Ok</div>
Copy the code
The above architectural ideas, however, need the consistency of team members to achieve the unity of code style.
What other ways are there to improve CSS quality besides these code specifications for development autonomy?
CSS preprocessor
In the preprocessor, there are also numerous ways to simplify and control CSS code, such as the Stylus
1. The variable
font-size = 14px
body
font font-size Arial, sans-serif
pad(types = padding, n = 5px)
if padding in types
padding n
if margin in types
margin n
body
pad()
body
pad(margin)
body
pad(padding margin.10px) / / Yields:body {
padding: 5px;
}
body {
margin: 5px;
}
body {
padding: 10px;
margin: 10px;
}
Copy the code
2. The function
add(a.b = a)
a + b
add(10.5) / / = >15
get(hash, key)
return pair[1] if pair[0] == key for pair in hash
hash = (one 1) (two 2) (three 3)
get(hash, two)
// => 2
get(hash, three)
// => 3
get(hash, something)
// => null
Copy the code
3. Built-in functions
// Extract the color component red(#c00) / / = >204
red(# 000.255) / / = >#f00
Copy the code
4. The interpolation
Vendor (prop, args) -webkit-{prop} args -moz-{prop} args {prop} argsborder-radius()
vendor('border-radius', arguments)
box-shadow()
vendor('box-shadow', arguments)
button
border-radius 1px 2px / 3px 4px
// Yields:
button {
-webkit-border-radius: 1px 2px / 3px 4px;
-moz-border-radius: 1px 2px / 3px 4px;
border-radius: 1px 2px / 3px 4px; } // Selector interpolationtable
for row in 1 2 3 4 5
tr:nth-child({row})
height: 10px * row
// Yields:
table tr:nth-child(1) {
height: 10px;
}
table tr:nth-child(2) {
height: 20px;
}
table tr:nth-child(3) {
height: 30px;
}
table tr:nth-child(4) {
height: 40px;
}
table tr:nth-child(5) {
height: 50px;
}
mySelectors = '#foo.#bar..baz'
{mySelectors}
background: # 000
Yields:
#foo,
#bar,
.baz {
background: # 000; } // Object interpolation foo = {width: 10px,
height: 20px.'&:hover': {
padding: 0}}.bar
{foo}
Yields:
// => .bar {
// width: 10px;
// height: 20px; / / / /}.bar:hover {
// padding: 0;
// }
Copy the code
5. @EXTEND
form
input[type=text]
padding: 5px
border: 1px solid #eee
color: #ddd
textarea
@extends form input[type=text]
padding: 10px
//Yielding:
form input[type=text],
textarea {
padding: 5px;
border: 1px solid #eee;
color: #ddd;
}
textarea {
padding: 10px;
}
Copy the code
Comments and spacing are essential to maintaining high quality CSS code
The following is a comparison of recommended comments and spacing that you can use on your own.
/*------------------------------------*\ #A-SECTION *------------------------------------*/
.selector{}/*------------------------------------*\ #ANOTHER-SECTION *------------------------------------*/
/** * Comment */
.another-selector{}Copy the code
In addition to indentation, we can provide a lot of information by using Spaces freely and wisely between rule sets. We use:
- A blank line (1) between closely related rule sets.
- Two (2) blank lines between loosely related rule sets.
- Five (5) empty lines between brand-new sections.
// good case
/*------------------------------------*\ #FOO *------------------------------------*/
.foo{}.foo__bar{}.foo--baz { }
// bad case
.foo{}.foo__bar{}.foo--baz{}Copy the code
The same rules apply to HTML structures.
In addition to the above, there are numerous specifications and optimizations that can continue to be explored, such as selector performance and CSS nesting, for the interested reader
You might think the CSS specification is a somewhat grand and unnecessary concept: why does something so simple and straightforward need to be designed to be as complex as architecture? !
It is precisely the simplicity, looseness, and unruly nature of CSS that means the best way to manage (read, tame) it at any reasonable scale is through strict and specific architectures. A solid architecture helps us control our particularity, enforce naming conventions, manage our source code order, create a robust development environment, and generally make our CSS project management more consistent and comfortable.
In summary, there are several rules that can be followed to create team/individual code specifications to ensure code consistency
A few principles are suggested
Single responsibility principle: Each CSS implementation must have a single responsibility.
Correct:
.button {
font-family: Arial, sans-serif;
border: 1px solid black;
background: #fff;
}
.header__button {
margin: 30px;
position: relative;
}
Incorrect:
.header__button {
font-family: Arial, sans-serif;
position: relative;
border: 1px solid black;
margin: 30px;
}
Copy the code
The open close principle: Elements should be extended by modifiers, not modified directly from the original.
Original:
<button class="button">... </button> .button { font-family: Arial, sans-serif;text-align: center;
font-size: 11px;
line-height: 20px;
}
Extend
<button class="buttonbutton_size_s">... </button>
.button {
font-family: Arial, sans-serif;
text-align: center;
font-size: 11px;
line-height: 20px;
}
.button_size_s {
font-size: 13px;
line-height: 24px;
}
Copy the code
The DRY principle: Normalize and abstract meaningful repetition
Mixin and extend@mixin my-web-font() {
font-family: "My Web Font", sans-serif;
font-weight: bold;
}
.btn {
display: inline-block;
padding: 1em 2em;
@include my-web-font();
}
.foo {
color: red;
}
.bar {
@extend .foo;
}
Copy the code
Composition is superior to inheritance and separation of concerns
// Write js in the same way as CSS<div class="layout">
<div class="layout__item two-thirds">
<section class="content">.</section>
</div>
<div class="layout__item one-third">
<section class="sub-content">.</section>
</div>
</div>
Copy the code
reference
BEM profile
OOCSS is introduced
Explore SMACSS: the extensible modular CSS framework
Write efficient CSS selectors
The single principle of CSS
Thinking about CSS architecture
❤️ Thank you
That is all the content of this sharing. I hope it will help you
Don’t forget to share, like and bookmark your favorite things.
Welcome to pay attention to the public number ELab team receiving factory good article ~
We are from the front end department of Bytedance, responsible for the front end development of all bytedance education products.
We focus on product quality improvement, development efficiency, creativity and cutting-edge technology and other aspects of precipitation and dissemination of professional knowledge and cases, to contribute experience value to the industry. Including but not limited to performance monitoring, component library, multi-terminal technology, Serverless, visual construction, audio and video, artificial intelligence, product design and marketing, etc.
Interested students are welcome to post in the comments section or use the internal tweet code to the author’s section at 🤪
Bytedance correction/social recruitment internal push code: 3DDR5K9
Post links: jobs.toutiao.com/s/dxqGR6p