Write CSS/Sass in a more sensible way

  • Disciplined code promotes teamwork,
  • The canonical code can be reducedbugTo deal with,
  • Regular code can reduce maintenance costs,
  • Normative code facilitates code review,
  • Getting into the habit of code specification helps programmers grow.

directory

The term

  • Rules that are
  • The selector
  • attribute

CSS

  • format
  • annotation
  • OOCSSBEM - IDThe selector
  • JavaScriptHook border

Sass

  • grammar
  • The sorting
  • variable
  • Mixins
  • Extension instructions
  • Nested selectors

The term

Rules that are

We call a selector (or set of) and a set of attributes a “rule declaration.” Here’s an example:

.listing {
  font-size: 18px;
  line-height: 1.2;
}
Copy the code

The selector

In the rule declaration, the “selector” is responsible for selecting the elements in the DOM tree, which will be decorated with defined attributes. Selectors can match HTML elements, as well as an element’s class name, ID, or attributes owned by the element. Here is an example of a selector:

.my-element-class {
  / *... * /
}
[aria-hidden] {
  / *... * /
}
Copy the code

attribute

Finally, attributes determine what style will be given to the selected element in the rule declaration. Properties exist as key-value pairs, and a rule declaration can contain one or more property definitions. Here is an example of an attribute definition:

/* some selector */ {
  background: #f1f1f1;
  color: # 333;
}
Copy the code

CSS

format

  • Use 2 Spaces for indentation.
  • It is recommended to use dashes instead of humps for class names. If you use BEM, you can also use underscores (see OOCSS and BEM below).
  • Do not use ID selectors.
  • When multiple selectors are applied to a rule declaration, each selector has a single row.
  • Open brace in rule declaration{Add a space before it.
  • The colon in the attribute:Followed by a space, followed by no space.
  • Close curly brace for rule declaration}Exclusive line.
  • Rule declarations are separated by blank lines.

Bad

.avatar{
    border-radius:50%;
    border:2px solid white; }
.no..nope..not_good{/ /... }#lol-no{/ /... }Copy the code

Good

.avatar {
  border-radius: 50%;
  border: 2px solid white;
}
.one..selector..per-line{/ /... }Copy the code

annotation

  • Line comments are recommended (in Sass they are//) instead of block comments.
  • It is recommended that comments be on a single line. Avoid end-of-line comments.
  • Write details for code that is not self-commented, such as:
    • Why z-index
    • Compatibility handling or browser-specific hacks

OOCSS and BEM

Some combination of OOCSS and BEM is encouraged for the following reasons:

  • It helps clarify the clear and rigorous relationship between CSS and HTML.
  • Helps us create reusable, easily assembled components.
  • You can reduce nesting, you can reduce specificity.
  • Helps us create extensible stylesheets.

OOCSS, or “Object Oriented CSS,” is a way of writing CSS that encourages you to think of stylesheets as collections of “objects” : creating reusable, repeatable pieces of code that you can use multiple times throughout your website.

References:

  • Nicole Sullivan 的 OOCSS wiki
  • Introduction to OOCSS by Smashing Magazine

BEM, or “block-element-Modifier,” is a naming convention for HTML and CSS class names. BEM was originally proposed by Yandex, given their huge code base and scalability, and can be used as a set of reference guidelines for OOCSS compliance.

  • CSS Trick BEM 101
  • Introduction to BEM by Harry Roberts

The sample

<article class="listing-card listing-card--featured">
  <h1 class="listing-card__title">Adorable 2BR in the sunny Mission</h1>
  <div class="listing-card__content">
    <p>Vestibulum id ligula porta felis euismod semper.</p>
  </div>
</article>
Copy the code
.listing-card{}.listing-card--featured{}.listing-card__title{}.listing-card__content{}Copy the code
  • .listing-cardIs a block, which represents a high-level component.
  • .listing-card__titleIs an element, “element.” It belongs to.listing-cardSo a block is made up of elements.
  • .listing-card--featuredIs a modifier that indicates that the block is connected.listing-cardHaving different states or variations.

The ID selector

In CSS, you can select elements by ID, but it’s often seen as a bad example. ID selectors give your rule declarations an unnecessarily high priority, and ID selectors are not reusable.

To learn more about this topic, see CSS Wizardry’s article on how to handle priorities.

JavaScript hooks

Avoid binding the same class in CSS and JavaScript. Otherwise, refactoring often results in developers wasting time looking for every class they want to change, or not making changes for fear of breaking functionality.

We recommend prefixing.js- when creating class names for specific JavaScript:

<button class="btn btn-primary js-request-to-book">Request to Book</button>
Copy the code

A border

Use 0 instead of None when defining a borderless style.

Bad

.foo {
  border: none;
}
Copy the code

Good

.foo {
  border: 0;
}
Copy the code

Sass

grammar

  • use.scssSyntax, do not use.sassThe original syntax.
  • CSS and@includeDeclarations are ordered logically (see below)

Sorting of property declarations

  1. The property declaration first lists the removal@includeAnd all property declarations except for nested selectors.
.btn-green {
  background: green;
  font-weight: bold;
  // ...
}
Copy the code
  1. @includeThe statement was followed by@include, which makes the whole selector more readable.
.btn-green {
  background: green;
  font-weight: bold;
  @include transition(background 0.5 s ease);
  // ...
}
Copy the code
  1. Nested selectorsIf necessaryTo use nested selectors, put them at the end, and add white space between the rule declaration and the nested selectors, as well as between the adjacent nested selectors. The contents of nested selectors also follow these guidelines.
.btn {
  background: green;
  font-weight: bold;
  @include transition(background 0.5 s ease);
  .icon {
    margin-right: 10px; }}Copy the code

variable

Variable names should use dashes (for example, $my-variable) instead of camelCased and snake_cased styles. For variables that are used only in the current file, prefix the variable name with an underscore (for example, $_my-variable).

Mixins

In order for code to follow the DRY principle (Don’t Repeat Yourself), enhance clarity, or abstract complexity, mixins should be used in the same way that well-named functions do. While mixins can take no parameters, be aware that if you don’t compress the load (via gzip, for example), the resulting style will contain unnecessary code duplication.

Extension instructions

The @extend directive should be avoided because it is unintuitive and potentially risky, especially when used with nested selectors. Even using extensions on top-level placeholder selectors can cause problems if the order of the selectors eventually changes. (For example, if they exist in other files and the loading order changes). In fact, most of the optimizations you get with @extend are already done by Gzip compression, so you just need mixins to make your stylesheets more DRY.

Nested selectors

Please do not let nested selectors be more than 3 layers deep!

.page-container {
  .content {
    .profile{ // STOP! }}}Copy the code

When encountering the above situations, you might write CSS like this:

  • Strong (and fragile) coupling to HTML– or –
  • Too specific (powerful)– or –
  • There is no reuse

Again: Never nest ID selectors!

If you insist on using ID selectors (think again), you shouldn’t nest them either. If you’re going to do this, you’ll need to re-check your tags first, or say why. If you want to write well-styled HTML and CSS, you shouldn’t.