Top Related Projects
High-level guidelines for writing manageable, maintainable CSS
The CSS design system that powers GitHub
Object Oriented CSS Framework
Standards for developing consistent, flexible, and sustainable HTML and CSS.
Style guides for Google-originated open-source projects
Quick Overview
Idiomatic CSS is a collection of principles for writing consistent, maintainable, and scalable CSS. It provides a set of guidelines and best practices for CSS authoring, aiming to improve code quality and collaboration among developers. The project serves as a style guide for writing CSS in a more structured and organized manner.
Pros
- Promotes consistency in CSS coding practices across teams and projects
- Improves code readability and maintainability
- Offers guidelines for handling common CSS challenges and edge cases
- Encourages modular and scalable CSS architecture
Cons
- Some guidelines may be subjective and not universally agreed upon
- Requires team buy-in and discipline to consistently follow the principles
- May require additional time and effort to implement in existing projects
- Some recommendations might conflict with personal preferences or project-specific requirements
Getting Started
To start using Idiomatic CSS principles in your project:
- Read through the guidelines in the README.md file.
- Implement the principles gradually in your CSS codebase.
- Consider creating a project-specific style guide based on these principles.
- Use linting tools like stylelint to enforce some of the guidelines automatically.
Example configuration for stylelint to enforce some Idiomatic CSS principles:
{
"rules": {
"indentation": 4,
"selector-list-comma-newline-after": "always",
"declaration-colon-space-after": "always",
"block-opening-brace-space-before": "always",
"property-case": "lower",
"color-hex-case": "lower",
"color-hex-length": "short",
"number-leading-zero": "always",
"string-quotes": "double",
"declaration-block-trailing-semicolon": "always"
}
}
Remember that Idiomatic CSS is not a strict ruleset but a set of guidelines. Adapt them to fit your project's needs and your team's preferences.
Competitor Comparisons
High-level guidelines for writing manageable, maintainable CSS
Pros of CSS-Guidelines
- More comprehensive and detailed explanations of CSS best practices
- Includes sections on performance optimization and scalability
- Provides practical examples and real-world scenarios
Cons of CSS-Guidelines
- Less focus on specific naming conventions
- May be overwhelming for beginners due to its extensive content
- Some recommendations might be considered opinionated
Code Comparison
CSS-Guidelines:
.c-button {
display: inline-block;
padding: 1em;
background-color: #eee;
}
.c-button--primary {
background-color: #4a90e2;
color: white;
}
Idiomatic CSS:
.btn {
display: inline-block;
padding: 1em;
background-color: #eee;
}
.btn-primary {
background-color: #4a90e2;
color: white;
}
Both repositories provide valuable guidelines for writing maintainable CSS. CSS-Guidelines offers a more in-depth approach with extensive explanations and examples, making it suitable for developers seeking comprehensive guidance. Idiomatic CSS, on the other hand, focuses on concise rules and naming conventions, which may be more appealing to those looking for a quick reference.
While CSS-Guidelines covers a broader range of topics, including performance and scalability, Idiomatic CSS emphasizes consistency in code style and structure. The code comparison shows slight differences in naming conventions, with CSS-Guidelines using BEM-like class names and Idiomatic CSS opting for simpler, hyphenated names.
The CSS design system that powers GitHub
Pros of Primer
- Comprehensive CSS framework with ready-to-use components
- Actively maintained with frequent updates and improvements
- Extensive documentation and examples for easy implementation
Cons of Primer
- Larger file size due to its comprehensive nature
- May require more effort to customize and override styles
- Steeper learning curve for developers new to the framework
Code Comparison
Idiomatic CSS:
.selector {
property: value;
property2: value2;
}
Primer:
.Selector {
property: var(--primer-property);
property2: var(--primer-property2);
}
Key Differences
- Idiomatic CSS focuses on best practices and coding style guidelines, while Primer is a full-fledged CSS framework.
- Idiomatic CSS provides a foundation for writing consistent, maintainable CSS, whereas Primer offers pre-built components and utility classes.
- Primer uses CSS variables extensively, allowing for easier theming and customization.
- Idiomatic CSS is more flexible and can be applied to any project, while Primer is tailored for GitHub-style interfaces.
Use Cases
- Choose Idiomatic CSS for projects requiring a custom design and full control over styles.
- Opt for Primer when building GitHub-like interfaces or needing a comprehensive design system with pre-built components.
Community and Support
- Idiomatic CSS has a smaller community but focuses on best practices discussions.
- Primer has a larger community and more resources due to its association with GitHub.
Object Oriented CSS Framework
Pros of OOCSS
- Promotes modular and reusable CSS, leading to more maintainable stylesheets
- Emphasizes separation of structure and skin, reducing code duplication
- Provides a methodology for creating scalable CSS architectures
Cons of OOCSS
- Can lead to more verbose HTML with multiple classes
- May require a steeper learning curve for developers new to the concept
- Potential for overuse of classes, which can make HTML less readable
Code Comparison
OOCSS approach:
.btn { /* Base button styles */ }
.btn-primary { /* Primary button styles */ }
.btn-large { /* Large button styles */ }
Idiomatic CSS approach:
.button {
/* Button styles */
}
.button--primary {
/* Primary button styles */
}
.button--large {
/* Large button styles */
}
The OOCSS approach uses multiple classes for modularity, while Idiomatic CSS follows a more BEM-like naming convention for component variations.
Standards for developing consistent, flexible, and sustainable HTML and CSS.
Pros of Code Guide
- More comprehensive, covering HTML, CSS, and some JavaScript
- Includes practical examples and explanations for each guideline
- Regularly updated with modern web development practices
Cons of Code Guide
- Less focused on CSS-specific best practices
- May be overwhelming for beginners due to its breadth of coverage
- Some guidelines are opinionated and may not align with all team preferences
Code Comparison
Idiomatic CSS:
.selector,
.selector-secondary,
.selector[type="text"] {
padding: 15px;
margin: 0 0 15px;
background-color: rgba(0,0,0,.5);
box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
}
Code Guide:
.selector {
padding: 15px;
margin-bottom: 15px;
background-color: rgba(0, 0, 0, 0.5);
box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
}
The Code Guide example emphasizes single selectors per rule and uses shorthand properties more sparingly, while Idiomatic CSS combines related selectors and uses more shorthand properties.
Style guides for Google-originated open-source projects
Pros of styleguide
- Comprehensive coverage of multiple programming languages
- Regularly updated and maintained by Google
- Includes tooling and linter configurations for easier adoption
Cons of styleguide
- Less focused on CSS-specific best practices
- More rigid and opinionated, which may not suit all projects
- Larger and more complex, potentially overwhelming for beginners
Code Comparison
idiomatic-css:
.selector,
.selector-secondary,
.selector[type="text"] {
padding: 15px;
margin: 0 0 15px;
background-color: rgba(0, 0, 0, 0.5);
box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
}
styleguide:
.example {
background: url(images/cat.png);
border: 1px solid #0000ff;
color: #fff;
margin: 0;
padding: 2em;
}
Summary
While styleguide offers a broader scope and more comprehensive guidelines for multiple languages, idiomatic-css provides a more focused approach to CSS best practices. styleguide benefits from Google's backing and regular updates but may be overwhelming for some users. idiomatic-css offers a simpler, more CSS-specific set of guidelines that may be easier to adopt for smaller projects or teams primarily focused on front-end development.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Principles of writing consistent, idiomatic CSS
The following document outlines a reasonable style guide for CSS development. These guidelines strongly encourage the use of existing, common, sensible patterns. They should be adapted as needed to create your own style guide.
This is a living document and new ideas are always welcome. Please contribute.
Table of contents
1. General principles
"Part of being a good steward to a successful project is realizing that writing code for yourself is a Bad Ideaâ¢. If thousands of people are using your code, then write your code for maximum clarity, not your personal preference of how to get clever within the spec." - Idan Gazit
- Don't try to prematurely optimize your code; keep it readable and understandable.
- All code in any code-base should look like a single person typed it, even when many people are contributing to it.
- Strictly enforce the agreed-upon style.
- If in doubt when deciding upon a style use existing, common patterns.
2. Whitespace
Only one style should exist across the entire source of your code-base. Always be consistent in your use of whitespace. Use whitespace to improve readability.
- Never mix spaces and tabs for indentation.
- Choose between soft indents (spaces) or real tabs. Stick to your choice without fail. (Preference: spaces)
- If using spaces, choose the number of characters used per indentation level. (Preference: 4 spaces)
Tip: configure your editor to "show invisibles" or to automatically remove end-of-line whitespace.
Tip: use an EditorConfig file (or equivalent) to help maintain the basic whitespace conventions that have been agreed for your code-base.
3. Comments
Well commented code is extremely important. Take time to describe components, how they work, their limitations, and the way they are constructed. Don't leave others in the team guessing as to the purpose of uncommon or non-obvious code.
Comment style should be simple and consistent within a single code base.
- Place comments on a new line above their subject.
- Keep line-length to a sensible maximum, e.g., 80 columns.
- Make liberal use of comments to break CSS code into discrete sections.
- Use "sentence case" comments and consistent text indentation.
Tip: configure your editor to provide you with shortcuts to output agreed-upon comment patterns.
Example:
/* ==========================================================================
Section comment block
========================================================================== */
/* Sub-section comment block
========================================================================== */
/**
* Short description using Doxygen-style comment format
*
* The first sentence of the long description starts here and continues on this
* line for a while finally concluding here at the end of this paragraph.
*
* The long description is ideal for more detailed explanations and
* documentation. It can include example HTML, URLs, or any other information
* that is deemed necessary or useful.
*
* @tag This is a tag named 'tag'
*
* TODO: This is a todo statement that describes an atomic task to be completed
* at a later date. It wraps after 80 characters and following lines are
* indented by 2 spaces.
*/
/* Basic comment */
4. Format
The chosen code format must ensure that code is: easy to read; easy to clearly comment; minimizes the chance of accidentally introducing errors; and results in useful diffs and blames.
- Use one discrete selector per line in multi-selector rulesets.
- Include a single space before the opening brace of a ruleset.
- Include one declaration per line in a declaration block.
- Use one level of indentation for each declaration.
- Include a single space after the colon of a declaration.
- Use lowercase and shorthand hex values, e.g.,
#aaa
. - Use single or double quotes consistently. Preference is for double quotes,
e.g.,
content: ""
. - Quote attribute values in selectors, e.g.,
input[type="checkbox"]
. - Where allowed, avoid specifying units for zero-values, e.g.,
margin: 0
. - Include a space after each comma in comma-separated property or function values.
- Include a semi-colon at the end of the last declaration in a declaration block.
- Place the closing brace of a ruleset in the same column as the first character of the ruleset.
- Separate each ruleset by a blank line.
.selector-1,
.selector-2,
.selector-3[type="text"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
display: block;
font-family: helvetica, arial, sans-serif;
color: #333;
background: #fff;
background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));
}
.selector-a,
.selector-b {
padding: 10px;
}
Declaration order
If declarations are to be consistently ordered, it should be in accordance with a single, simple principle.
Smaller teams may prefer to cluster related properties (e.g. positioning and box-model) together.
.selector {
/* Positioning */
position: absolute;
z-index: 10;
top: 0;
right: 0;
bottom: 0;
left: 0;
/* Display & Box Model */
display: inline-block;
overflow: hidden;
box-sizing: border-box;
width: 100px;
height: 100px;
padding: 10px;
border: 10px solid #333;
margin: 10px;
/* Other */
background: #000;
color: #fff;
font-family: sans-serif;
font-size: 16px;
text-align: right;
}
Larger teams may prefer the simplicity and ease-of-maintenance that comes with alphabetical ordering.
Exceptions and slight deviations
Large blocks of single declarations can use a slightly different, single-line format. In this case, a space should be included after the opening brace and before the closing brace.
.selector-1 { width: 10%; }
.selector-2 { width: 20%; }
.selector-3 { width: 30%; }
Long, comma-separated property values - such as collections of gradients or shadows - can be arranged across multiple lines in an effort to improve readability and produce more useful diffs. There are various formats that could be used; one example is shown below.
.selector {
background-image:
linear-gradient(#fff, #ccc),
linear-gradient(#f3c, #4ec);
box-shadow:
1px 1px 1px #000,
2px 2px 1px 1px #ccc inset;
}
Preprocessors: additional format considerations
Different CSS preprocessors have different features, functionality, and syntax. Your conventions should be extended to accommodate the particularities of any preprocessor in use. The following guidelines are in reference to Sass.
- Limit nesting to 1 level deep. Reassess any nesting more than 2 levels deep. This prevents overly-specific CSS selectors.
- Avoid large numbers of nested rules. Break them up when readability starts to be affected. Preference to avoid nesting that spreads over more than 20 lines.
- Always place
@extend
statements on the first lines of a declaration block. - Where possible, group
@include
statements at the top of a declaration block, after any@extend
statements. - Consider prefixing custom functions with
x-
or another namespace. This helps to avoid any potential to confuse your function with a native CSS function, or to clash with functions from libraries.
.selector-1 {
@extend .other-rule;
@include clearfix();
@include box-sizing(border-box);
width: x-grid-unit(1);
// other declarations
}
5. Practical example
An example of various conventions.
/* ==========================================================================
Grid layout
========================================================================== */
/**
* Column layout with horizontal scroll.
*
* This creates a single row of full-height, non-wrapping columns that can
* be browsed horizontally within their parent.
*
* Example HTML:
*
* <div class="grid">
* <div class="cell cell-3"></div>
* <div class="cell cell-3"></div>
* <div class="cell cell-3"></div>
* </div>
*/
/**
* Grid container
*
* Must only contain `.cell` children.
*
* 1. Remove inter-cell whitespace
* 2. Prevent inline-block cells wrapping
*/
.grid {
height: 100%;
font-size: 0; /* 1 */
white-space: nowrap; /* 2 */
}
/**
* Grid cells
*
* No explicit width by default. Extend with `.cell-n` classes.
*
* 1. Set the inter-cell spacing
* 2. Reset white-space inherited from `.grid`
* 3. Reset font-size inherited from `.grid`
*/
.cell {
position: relative;
display: inline-block;
overflow: hidden;
box-sizing: border-box;
height: 100%;
padding: 0 10px; /* 1 */
border: 2px solid #333;
vertical-align: top;
white-space: normal; /* 2 */
font-size: 16px; /* 3 */
}
/* Cell states */
.cell.is-animating {
background-color: #fffdec;
}
/* Cell dimensions
========================================================================== */
.cell-1 { width: 10%; }
.cell-2 { width: 20%; }
.cell-3 { width: 30%; }
.cell-4 { width: 40%; }
.cell-5 { width: 50%; }
/* Cell modifiers
========================================================================== */
.cell--detail,
.cell--important {
border-width: 4px;
}
Translations
- Bahasa Indonesia
- Bulgarian
- Äesky
- Dansk
- Deutsch
- Español
- Français
- Italiano
- æ¥æ¬èª
- íêµì´
- Nederlands
- Polski
- Português (Brasil)
- Ð ÑÑÑкий
- Srpski
- Türkçe
- æ£é«ä¸æ
- ç®ä½ä¸æ
Acknowledgements
Thanks to everyone who has provided translations and to all those who contributed to idiomatic.js. It was a source of inspiration, quotations, and guidelines.
License
Principles of writing consistent, idiomatic CSS by Nicolas Gallagher is licensed under the Creative Commons Attribution 3.0 Unported License. This applies to all documents and translations in this repository.
Based on a work at github.com/necolas/idiomatic-css.
Top Related Projects
High-level guidelines for writing manageable, maintainable CSS
The CSS design system that powers GitHub
Object Oriented CSS Framework
Standards for developing consistent, flexible, and sustainable HTML and CSS.
Style guides for Google-originated open-source projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot