Pendekatan yang umum dan terbaik untuk CSS dan Sass
“rule declaration” merupakan nama yang diberikan kepada sesuatu selector (atau daripada beberapa selectors) dengan properties yang berada di dalamnya. Sebagai contoh:
.listing {
font-size: 18px;
line-height: 1.2;
}
dalam rule declaration, “selectors” adalah penentu dimana element di dalam DOM tree akan diberikan style dengan men-declare-kan properties di dalamnya. Selectors boleh dipadankan dengan HTML elements, dan juga element's class, ID, atau mana-mana attributes. Di sini adalah sebahagian contoh kepada selectors:
.my-element-class {
/* ... */
}
[aria-hidden] {
/* ... */
}
Akhirnya, tugas properties adalah memberikan elements yang dipilih sesuatu style. Properties adalah pasangan key-value, dan rule declaration boleh mengandungi satu atau lebih property declarations. Property declarations seperti berikut:
/* some selector */ {
background: #f1f1f1;
color: #333;
}
- Gunakan soft tabs (2 spaces) untuk melakukan indent.
- Lebih baik menggunakan dashes berbanding camelCasing di dalam nama class.
- Underscores(_) dan PascalCasing adalah baik jika kamu menggunakan BEM (lihat OOCSS and BEM dibawah).
- Jangan menggunakan ID selectors.
- Apabila menggunakan banyak selectors dalam rule declaration, berikan setiap selector mempunyai baris baru.
- Berikan space sebelum buka kurungan
{
dalam rule declarations. - Dalam properties, letakkan space selepas, tetapi bukan sebelumnya dari karekter
:
. - Letak penutup kurungan
}
daripada rule declarations kemudian tambah baris baru. - Letak baris kosong antara rule declarations.
Teruk
.avatar{
border-radius:50%;
border:2px solid white; }
.no, .nope, .not_good {
// ...
}
#lol-no {
// ...
}
Bagus
.avatar {
border-radius: 50%;
border: 2px solid white;
}
.one,
.selector,
.per-line {
// ...
}
- Prefer line comments (
//
in Sass-land) to block comments. - Prefer comments on their own line. Avoid end-of-line comments.
- Write detailed comments for code that isn't self-documenting:
- Uses of z-index
- Compatibility or browser-specific hacks
We encourage some combination of OOCSS and BEM for these reasons:
- It helps create clear, strict relationships between CSS and HTML
- It helps us create reusable, composable components
- It allows for less nesting and lower specificity
- It helps in building scalable stylesheets
OOCSS, or “Object Oriented CSS”, is an approach for writing CSS that encourages you to think about your stylesheets as a collection of “objects”: reusable, repeatable snippets that can be used independently throughout a website.
- Nicole Sullivan's OOCSS wiki
- Smashing Magazine's Introduction to OOCSS
BEM, or “Block-Element-Modifier”, is a naming convention for classes in HTML and CSS. It was originally developed by Yandex with large codebases and scalability in mind, and can serve as a solid set of guidelines for implementing OOCSS.
- CSS Trick's BEM 101
- Harry Roberts' introduction to BEM
We recommend a variant of BEM with PascalCased “blocks”, which works particularly well when combined with components (e.g. React). Underscores and dashes are still used for modifiers and children.
Example
// ListingCard.jsx
function ListingCard() {
return (
<article class="ListingCard ListingCard--featured">
<h1 class="ListingCard__title">Adorable 2BR in the sunny Mission</h1>
<div class="ListingCard__content">
<p>Vestibulum id ligula porta felis euismod semper.</p>
</div>
</article>
);
}
/* ListingCard.css */
.ListingCard { }
.ListingCard--featured { }
.ListingCard__title { }
.ListingCard__content { }
.ListingCard
is the “block” and represents the higher-level component.ListingCard__title
is an “element” and represents a descendant of.ListingCard
that helps compose the block as a whole..ListingCard--featured
is a “modifier” and represents a different state or variation on the.ListingCard
block.
While it is possible to select elements by ID in CSS, it should generally be considered an anti-pattern. ID selectors introduce an unnecessarily high level of specificity to your rule declarations, and they are not reusable.
For more on this subject, read CSS Wizardry's article on dealing with specificity.
Avoid binding to the same class in both your CSS and JavaScript. Conflating the two often leads to, at a minimum, time wasted during refactoring when a developer must cross-reference each class they are changing, and at its worst, developers being afraid to make changes for fear of breaking functionality.
We recommend creating JavaScript-specific classes to bind to, prefixed with .js-
:
<button class="btn btn-primary js-request-to-book">Request to Book</button>
Use 0
instead of none
to specify that a style has no border.
Bad
.foo {
border: none;
}
Good
.foo {
border: 0;
}
- Use the
.scss
syntax, never the original.sass
syntax - Order your regular CSS and
@include
declarations logically (see below)
-
Property declarations
List all standard property declarations, anything that isn't an
@include
or a nested selector..btn-green { background: green; font-weight: bold; // ... }
-
@include
declarationsGrouping
@include
s at the end makes it easier to read the entire selector..btn-green { background: green; font-weight: bold; @include transition(background 0.5s ease); // ... }
-
Nested selectors
Nested selectors, if necessary, go last, and nothing goes after them. Add whitespace between your rule declarations and nested selectors, as well as between adjacent nested selectors. Apply the same guidelines as above to your nested selectors.
.btn { background: green; font-weight: bold; @include transition(background 0.5s ease); .icon { margin-right: 10px; } }
Prefer dash-cased variable names (e.g. $my-variable
) over camelCased or snake_cased variable names. It is acceptable to prefix variable names that are intended to be used only within the same file with an underscore (e.g. $_my-variable
).
Mixins should be used to DRY up your code, add clarity, or abstract complexity--in much the same way as well-named functions. Mixins that accept no arguments can be useful for this, but note that if you are not compressing your payload (e.g. gzip), this may contribute to unnecessary code duplication in the resulting styles.
@extend
seharusnya dihindari kerana it has unintuitive and potentially dangerous behavior, especially when used with nested selectors. Even extending top-level placeholder selectors can cause problems if the order of selectors ends up changing later (e.g. if they are in other files and the order the files are loaded shifts). Gzipping should handle most of the savings you would have gained by using @extend
, and you can DRY up your stylesheets nicely with mixins.
Jangan mengunakan nested selectors lebih daripada tiga level!
.page-container {
.content {
.profile {
// STOP!
}
}
}
Jika selectors menjadi terlalu panjang, Kamu telah menulis CSS seperti ini:
- Terlalu banyak gabungan terhadap HTML (fragile) —OR—
- Terlalu spesifik (powerful) —OR—
- Tidak reusable
Sekali Lagi: Jangan pernah nesting ID selectors!
Jika kamu wajib menggunakan ID selector di tempat pertama(dan kamu mesti benar-benar mencuba tidak melakukannya), mereka tidak boleh nested. Jika kamu menemukan melakukan hal ini, kamu perlu untuk meninjau kembali markup anda atau belajar mengapa hal tersebut diperlukan. Jika kamu menulis dengan baik HTML dan CSS, kamu seharusnya tidak pernah melakukan hal seperti itu.
Panduan style ini juga tersedia dalam bahasa yang lain:
Bahasa Indonesia: mazipan/css-style-guide
Chinese (Traditional): ArvinH/css-style-guide
Chinese (Simplified): Zhangjd/css-style-guide
French: mat-u/css-style-guide
Japanese: nao215/css-style-guide
Korean: CodeMakeBros/css-style-guide
Portuguese (Brazil): felipevolpatto/css-style-guide
Portuguese (Portugal): SandroMiguel/airbnb-css-style-guide
Russian: rtplv/airbnb-css-ru
Spanish: ismamz/guia-de-estilo-css
Vietnamese: trungk18/css-style-guide
Italian: antoniofull/linee-guida-css
German: tderflinger/css-styleguide
(The MIT License)
Copyright (c) 2015 Airbnb
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.