Coder Social home page Coder Social logo

css's Introduction

Airbnb CSS / Sass Styleguide

A mostly reasonable approach to CSS and Sass

Table of Contents

  1. Terminology
  2. CSS
  3. Sass
  4. Translation
  5. License

Terminology

Rule declaration

A “rule declaration” is the name given to a selector (or a group of selectors) with an accompanying group of properties. Here's an example:

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

Selectors

In a rule declaration, “selectors” are the bits that determine which elements in the DOM tree will be styled by the defined properties. Selectors can match HTML elements, as well as an element's class, ID, or any of its attributes. Here are some examples of selectors:

.my-element-class {
  /* ... */
}

[aria-hidden] {
  /* ... */
}

Properties

Finally, properties are what give the selected elements of a rule declaration their style. Properties are key-value pairs, and a rule declaration can contain one or more property declarations. Property declarations look like this:

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

⬆ back to top

CSS

Formatting

  • Use soft tabs (2 spaces) for indentation.
  • Prefer dashes over camelCasing in class names.
    • Underscores and PascalCasing are okay if you are using BEM (see OOCSS and BEM below).
  • Do not use ID selectors.
  • When using multiple selectors in a rule declaration, give each selector its own line.
  • Put a space before the opening brace { in rule declarations.
  • In properties, put a space after, but not before, the : character.
  • Put closing braces } of rule declarations on a new line.
  • Put blank lines between rule declarations.

Bad

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

Good

.avatar {
  border-radius: 50%;
  border: 2px solid white;
}

.one,
.selector,
.per-line {
  // ...
}

Comments

  • 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

OOCSS and BEM

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.

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.

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.

ID selectors

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.

JavaScript hooks

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>

Border

Use 0 instead of none to specify that a style has no border.

Bad

.foo {
  border: none;
}

Good

.foo {
  border: 0;
}

⬆ back to top

Sass

Syntax

  • Use the .scss syntax, never the original .sass syntax
  • Order your regular CSS and @include declarations logically (see below)

Ordering of property declarations

  1. Property declarations

    List all standard property declarations, anything that isn't an @include or a nested selector.

    .btn-green {
      background: green;
      font-weight: bold;
      // ...
    }
  2. @include declarations

    Grouping @includes at the end makes it easier to read the entire selector.

    .btn-green {
      background: green;
      font-weight: bold;
      @include transition(background 0.5s ease);
      // ...
    }
  3. 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;
      }
    }

Variables

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

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 directive

@extend should be avoided because 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.

Nested selectors

Do not nest selectors more than three levels deep!

.page-container {
  .content {
    .profile {
      // STOP!
    }
  }
}

When selectors become this long, you're likely writing CSS that is:

  • Strongly coupled to the HTML (fragile) —OR—
  • Overly specific (powerful) —OR—
  • Not reusable

Again: never nest ID selectors!

If you must use an ID selector in the first place (and you should really try not to), they should never be nested. If you find yourself doing this, you need to revisit your markup, or figure out why such strong specificity is needed. If you are writing well formed HTML and CSS, you should never need to do this.

⬆ back to top

Translation

This style guide is also available in other languages:

⬆ back to top

License

(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.

⬆ back to top

css's People

Contributors

andrewjrhill avatar antoniofull avatar arvinh avatar backwardok avatar davidkadaria avatar divyamoncy avatar felipevolpatto avatar ismamz avatar lencioni avatar ljharb avatar mat-u avatar mikefowler avatar nao215 avatar nekorsis avatar tderflinger avatar trungvose avatar victorlss avatar zhangjd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

css's Issues

Bahasa Indonesia translation

As Indonesian developer, I want other developer can read this style guide with our own language.
because many of our developer have poor English knowledge so I propose for this request

May this be a npm package ?

Hello,
I think this should be a npm package so Sass lint can have the .yml file from the npm package.
Obviously we may copy/paste the .yml file but for well known reasons using npm packages are better than copy pasting needed dependencies (auto updates, more maintainable, better for git etc.)

What the pros/cons of using Airbnb CSS / Sass Styleguide?

Hi there,

I hope you are doing well. Currently, I'm preparing a presentation for KharkivCSS (Ukrainian tech event). My talk will cover a lot of topics. Some of them you can find below:

  • What is CSS Style guide;
  • Why it's important to use it;
  • How to start from scratch if you don't have any CSS Style Guides;
  • Metrics;
  • And so on.

I would like to ask you a few questions:

  1. What the main reason did you follow when you decided to develop Airbnb CSS / Sass Style Guide?
  2. Do you have any info which metrics have you improved, e.g. the counts of bugs/issues, time for development for a new feature, the size of components, etc?
  3. Do you have any kind of Living Style Guide system based on your CSS / Sass Style Guide?

#CSSStyleGuide #CSSMatters #CSSStyleGuideMatters

Best regards,
Vitalii

Nested media-queries

I've found no mention of media-queries here so I've got a question.

If I'm using SCSS or PostCSS Nested plugin, does Airbnb styleguide allow to use nested media-queries (media query bubbling, saying more precisely)? And if so, how much more preferable to use it in comparison with using regular media-queries?

Add license

Would it be possible to add a license to this repository? We would like to use it as the basis for our own internal styleguide, but don't want to violate any copyright laws.

Border Section

Can anyone help explain me why we should use border: 0; instead of border: none;?

Move to sass-lint

The Sass core team is now building Sass in Dart instead of Ruby, and will no longer be maintaining the Ruby implementation unless a maintainer steps up to help. Since the SCSS-Lint project relies on the Ruby Sass implementation, this means it will eventually not support the latest Sass features and bug fixes.

So moving to sass-lint seems the right thing to do. Especially that sass-lint is on npm. Both sass-lint and scss-lint should be close.
I may create a PR to create a sass-lint if you agree. I prefer open issue and a PR as it may have multiple changes (Readme, the .sass-lint.yml file, we may delete the .scss-lint.yml file etc.)

stylelint-config-airbnb is causing issues with npm for dependency resolution

when installing stylelint and stylelint-config-airbnb, I get the following npm Error:
npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] npm ERR! node_modules/stylelint npm ERR! dev stylelint@"*" from the root project npm ERR! peer stylelint@"^8.0.0" from [email protected] npm ERR! node_modules/stylelint-config-airbnb npm ERR! dev stylelint-config-airbnb@"*" from the root project npm ERR! 1 more (stylelint-order) npm ERR! npm ERR! Could not resolve dependency: npm ERR! dev stylelint-config-prettier@"*" from the root project npm ERR! npm ERR! Conflicting peer dependency: [email protected] npm ERR! node_modules/stylelint npm ERR! peer stylelint@">=11.0.0" from [email protected] npm ERR! node_modules/stylelint-config-prettier npm ERR! dev stylelint-config-prettier@"*" from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force, or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

remove the stylelint-config-airbnb, then no more problem. Of course, if one want to use stylelint-config-airbnb, then this is not a good solution. That is why I am reporting the issue here

How do I translate it to Catalan?

I am a Catalan native speaker. How do I translate this to Catalan? Do I create my own repository with the translation and then make a pull request to your repository with the link to my translated repository?

Menu

Full screen navigation

stylelint-config-airbnb package's dep includes high priority vulnerability

Could you please update stylelint-config-airbnb package's dependencies, as these include high priority vulnerabilities?

npm audit

  High            Prototype Pollution                                           

  Package         lodash                                                        

  Patched in      >=4.17.11                                                     

  Dependency of   stylelint-config-airbnb [dev]                                 

  Path            stylelint-config-airbnb > editorconfig-tools > lodash         

  More info       https://npmjs.com/advisories/782                              


  High            Prototype Pollution                                           

  Package         lodash                                                        

  Patched in      >=4.17.12                                                     

  Dependency of   stylelint-config-airbnb [dev]                                 

  Path            stylelint-config-airbnb > editorconfig-tools > lodash         

  More info       https://npmjs.com/advisories/1065                             


  Moderate        Regular Expression Denial of Service                          

  Package         underscore.string                                             

  Patched in      >=3.3.5                                                       

  Dependency of   stylelint-config-airbnb [dev]                                 

  Path            stylelint-config-airbnb > editorconfig-tools > argparse >     
                  underscore.string                                             

  More info       https://npmjs.com/advisories/745     

How to override the css styles

I have used on the Cascade Style Sheet,

To i should cannot override to write the styles in html page

How to override to write any sample code give.

yarn lint warning about deprecated rule

hello, I came from here

stylelint/stylelint#5478

I got 'Deprecation Warning: 'declaration-property-value-blacklist' has been deprecated. Instead use 'declaration-property-value-disallowed-list'. See: https://github.com/stylelint/stylelint/blob/13.7.0/lib/rules/declaration-property-value-blacklist/README.md' error

stylelint.config.js

module.exports = {
  extends: [
    'stylelint-config-standard',
    // 'stylelint-config-airbnb',
    'stylelint-config-prettier',
  ],
  plugins: ['stylelint-scss', 'stylelint-order'],
  rules: {},
};

and if i remove stylelint-config-airbnb from extends, it works well.
can you check this for me?

Thank you! :)

Stylinter stopped working with stylelint-config-airbnb

Here is exact code

When i run it manually via

cat src/components/song/song.css | /Users/artem/Desktop/MuzicBox/src/front_end/node_modules/.bin/stylelint --formatter json --stdin-filename /Users/artem/Desktop/MuzicBox/src/front_end/src/components/song/song.css

it shows

[{"source":"/Users/artem/Desktop/MuzicBox/src/front_end/src/components/song/song.css","deprecations":[],"invalidOptionWarnings":[],"parseErrors":[],"warnings":[]}]%

But when i use stylelint-config-standard and run manually in the same way as above i get

[{"source":"/Users/artem/Desktop/MuzicBox/src/front_end/src/components/song/song.css","deprecations":[],"invalidOptionWarnings":[],"parseErrors":[],"errored":true,"warnings":[{"line":205,"column":1,"rule":"max-empty-lines","severity":"error","text":"Expected no more than 1 empty line (max-empty-lines)"},{"line":206,"column":1,"rule":"max-empty-lines","severity":"error","text":"Expected no more than 1 empty line (max-empty-lines)"},{"line":6,"column":41,"rule":"number-leading-zero","severity":"error","text":"Expected a leading zero (number-leading-zero)"},{"line":106,"column":29,"rule":"number-leading-zero","severity":"error","text":"Expected a leading zero (number-leading-zero)"},{"line":208,"column":14,"rule":"number-leading-zero","severity":"error","text":"Expected a leading zero (number-leading-zero)"},{"line":219,"column":24,"rule":"number-leading-zero","severity":"error","text":"Expected a leading zero (number-leading-zero)"},{"line":230,"column":3,"rule":"rule-empty-line-before","severity":"error","text":"Unexpected empty line before rule (rule-empty-line-before)"}]}]%

PascalCase on Block selectors for React

I like the idea of this. I know we don't want to conform SO much to React because we may not use it forever. I think this makes sense though when it is necessary to use a React class as a namespace in CSS and it is easy enough to edit down the road. Just want to make sure this is cool with everyone to move forward using PascalCase on block elements (using BEM)

How to override the css styles

I have used on the Cascade Style Sheet and try to override the style.

but cannot override to write the styles in html page

How to override to write any sample code give.

Handling typography

What's the airbnb approach to styling typography? Is it advisable to select type-specific elements (p, header elements) and set their font-size, line-height and font-weight versus labeling each element with classes such as "normal-body", "small-body" ? should these classes be considered utility classes and be used in exceptional cases?

npm package

Couldn't it be useful to have an npm package for this one? :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.