CSS Authoring Guidelines and recommendations

Source: Internet
Author: User
Tags new set css preprocessor

It is extremely important for all developers to adhere to the following rules when participating in a large, long-lasting and participatory project:

    • Keep CSS easy to maintain
    • Keep your code clear and understandable
    • Maintain CSS Extensibility

In order to achieve this goal, we have to adopt many methods.

The first part of this document explores the syntax, format, and parsing of CSS structures, and the second part revolves around methodologies, thinking frameworks, and the idea of writing and planning CSS.

CSS Document Analysis

No matter what documentation is written, we should maintain a unified style, including uniform annotations, uniform syntax, and uniform naming conventions.

General

Control the line width below 80 bytes. The syntax associated with gradients (gradient) and the URLs in comments can be counted as exceptions, after all.

I tend to use 4 spaces instead of Tab indents, and split the declaration into multiple lines.

Single file with multiple files

Someone likes to write all the content in a file, and I start splitting the style into smaller files after migrating to Sass. This is all very well done. Whichever you choose, the rules below will apply, and you will not encounter any problems if you follow these rules. The difference between these two types of writing is only the table of contents and the block headings:

Directory

At the beginning of the CSS, I will maintain a directory, just like this:

/*------------------------------------*    $CONTENTS \*------------------------------------*//** * CONTENTS ............ You ' re reading it! * RESET ...... ..... Set our reset defaults * Font-face ..... Import Brand Font Files */

This catalogue can tell other developers exactly what is in this file. Each item in this directory is the same as its corresponding chunk title.

If you are maintaining a single-file CSS, the corresponding chunks will also be in the same file. If you are writing a small set of files, then each item in the directory should correspond to the corresponding @include statement.

Chunk title

The directory should correspond to the title of the block. As follows:

/*------------------------------------*    $RESET \*------------------------------------*/

The chunk header prefix $ allows us to use [cmd| The Ctrl]+f command finds the title name when the search scope is limited to the chunk header.

If you are maintaining a large file, then empty 5 lines between the chunks, as follows:

/*------------------------------------*    $RESET \*------------------------------------*/[ourresetstyles]/*-- ----------------------------------*    $FONT-face\*------------------------------------* *

These large gaps help distinguish chunks when quickly flipping through large files.

If you are maintaining multiple CSS with include connections, add a title to each file header, so you don't have to do this.

Code Order

Try to write the rules in a specific order, which will ensure you get the most out of the first C in CSS: Cascade, cascading.

A well-planned CSS should be arranged as follows:

    1. Reset the root of everything
    2. Element type does not have class H1, UL, etc.
    3. The most general and basic design patterns for objects and abstract content
    4. All extensions and child elements of child elements that are extended by the object
    5. Patching for exception status

This way, when you write CSS in turn, each chunk can automatically inherit the properties of the block before it. This reduces the number of parts that the code cancels out of each other, reduces some special problems, and makes up a more desirable CSS structure.

For more information on this, Jonathan Snook's smacss is highly recommended.

CSS Style Set Analysis
[Selector] {    [property]:[value];    [<-Declaration->]} [Selector] {    [attribute]:[value];    [<-statement->]}

I am accustomed to following these rules when writing CSS styles:

    • The class name is concatenated with a hyphen (-), except for the BEM nomenclature mentioned below;
    • Indent 4 spaces;
    • The declaration is split into multiple lines;
    • Declarations are arranged in the order of relevance, not alphabetical order;
    • The prefixed declarations are indented appropriately to align their values;
    • Indents the style set to reflect the DOM;
    • Keep the semicolon at the end of the last declaration.

For example:

. widget{    padding:10px;    border:1px solid #BADA55;    Background-color: #C0FFEE;    -webkit-border-radius:4px;       -moz-border-radius:4px;            border-radius:4px;}    . widget-heading{        Font-size:1.5rem;        line-height:1;        Font-weight:bold;        Color: #BADA55;        margin-right:-10px;        Margin-left: -10px;        padding:0.25em;    }

We can find that. widget-heading is a child of the. Widget, because the former has a more indented style set than the latter. This allows developers to quickly get such important information as they read the code by indenting it.

We can also find that the declaration of the. Widget-heading is arranged according to its relevance:. Widget-heading is an inline element, so let's add a font-related style declaration first, and then the rest.

Here is an example that is not split into multiple lines:

. T10    {width:10%}.t20    {width:20%}.t25    {width:25%}/*-*/.t30    {width:30%}.t33    {width:33 .333%}/   * 1/3 */.t40    {width:40%}.t50    {width:50%}/       * */.t60    {    width:60%}.t66 {width:66 .666%}   /* 2/3 */.t70    {width:70%}.t75    {width:75%}/       * 3/4*/.t80    {width:80%}.t90    {Widt h:90%}

In this example (from the INUIT.CSS's Table grid system), putting CSS in one line can make the code more compact.

Naming conventions

In general, I connect the name of class with a hyphen (-) (for example,. Foo-bar instead of. Foo_bar or. fooBar), but at certain times I use BEM (Block, Element, Modifier) nomenclature.

BEM nomenclature can make selectors more normative, clearer, and more semantic.

The nomenclature is in the following format:

. block{}.block__element{}.block--modifier{}

which

    • The. Block represents a basic abstraction element;
    • . block__element represents a sub-element of the block.
    • . Block--modifier represents a different state or version of the. Block.

To make an analogy:

. person{}.person--woman{}    . person__hand{}    . person__hand--left{}    . person__hand--right{}

The basic element we describe in this example is a person, and then this person may be a woman. We also know that people have hands, these are part of the human body, and the hands have different states, like the left hand and the right hand.

This allows us to delimit the selector's namespace based on the pro element and convey the function of the selector, for example, depending on whether the selector is a child element (__) or a different state (--) of its parent element.

From this,. Page-wrapper is a standalone selector. This is a canonical naming because it is not a child or other state of other elements, whereas. Widget-heading is associated with other objects, which should be child elements of the. Widget, so we should rename it to. widget__heading.

The BEM nomenclature is not very good-looking, but rather lengthy, but it allows us to quickly learn the relationship between the function of an element and the element by its name. At the same time, the repeating part of the BEM syntax is very advantageous to the GZIP compression algorithm.

Whether or not you use the BEM nomenclature, you should make sure that class is well-named, with a few words, a few words, and an abstraction of the element name to improve reusability (for example,. ui-list,.media). The name of the child element should be as accurate as possible (for example,. user-avatar-link). Don't worry about the number or length of the class name, because a well-written code, gzip, can compress effectively.

The class in HTML

To ensure legibility, the class name is separated by two spaces in the HTML tag, for example:

<div class= "Foo--bar  Bar__baz" >

The added space should make it easier to read and position when using multiple classes.

JavaScript Hooks

Never use the class labeled CSS style as a JavaScript hook. If you mix JS behavior with style, you can't handle it separately.

If you want to bind JS with some tags, write a JS-specific class. In short, a prefix is delimited. js-namespaces, such as. Js-toggle,.js-drag-and-drop. This means that we can bind JS and CSS through class at the same time without causing trouble because of conflict.

<th class= "is-sortable  js-is-sortable" ></th>

The above tag has two classes, and you can use one to add a style to the sortable table bar and another to add the sorting function.

i18n

Although I (the original author of the CSS guideline document, Harry Roberts) was an Englishman, and I always spelled colour rather than color, I thought it would be better to have the American spelling in CSS in order to pursue unity. CSS and most other languages are written in American spelling, so if you write color:red in. colour-picker{} it lacks uniformity. I previously advocated using two spellings at the same time, for example:

. color-picker,.colour-picker{}

But I recently participated in a large-scale Sass project, which has many color variables (e.g. $brand-color, $highlight-color, etc.), it is hard to maintain two kinds of spelling for each variable, and it takes twice times more work to find and replace.

So in order to unify, all classes and variables are named in the customary spelling of the project you are involved in.

Comments

I use a document block style comment with a line width of not more than 80 bytes:

/** * This was a docblock style comment *  * This was a longer description of the comment, describing the code in more * Detail. We limit these lines to a maximum of more characters in length. *  We can have markup in the comments, and is encouraged to doing so: *    <div class= "foo" >       <p>lorem& lt;/p>   </div> * * We don't prefix lines of code with a asterisk as to doing so  would inhibit * copy and PA Ste. *//** * This is a document block (DocBlock) style comment. * * This starts with a more detailed and lengthy comment body. Of course, we have to control the line width within 80 bytes. * * We can embed HTML tags in comments, and that's a good idea: *    <div class= "foo" >        <p>Lorem</p>    </div> * * If the tag is embedded in the comment, it is not preceded by an asterisk so as not to be copied in. */

The code should be described in detail as much as possible in the comments, because content that is clear to you may not be the case for other people. Each part of the code will be written in special comments to explain.

Extended usage of annotations

Note There are many very high-level uses, such as:

    • Quasi-modifier selector (quasi-qualified selectors)
    • Code tags
    • Inheritance Tags
Quasi-modifier selector (quasi-qualified selectors)

You should avoid overly modifying selectors, for example if you can write. nav{} try not to write ul.nav{}. An overly-modified selector will affect performance, affect class reusability, and increase the selector's private degree. These are all things you should try to avoid.

But sometimes you might want to tell other developers what class to use. In. Product-page, for example, this class looks like a root container, possibly an HTML or BODY element, but it cannot be judged by the. Product-page.

We can describe our planned class scope by adding a quasi-modifier (which will comment out the preceding type selector) before the selector:

/*html*/.product-page{}

This allows us to accurately know the scope of the class without compromising reusability.

Other examples are as follows:

/*ol*/.breadcrumb{}/*p*/.intro{}/*ul*/.image-thumbs{}

This allows us to know the scope of the class without compromising the private degree of the code.

Code tags

If you write a new set of styles, you can add tags to it, for example:

/** * ^navigation ^lists */.nav{}/** * ^grids ^lists ^tables */.matrix{}

These tags can enable other developers to quickly find the relevant code. If a developer needs to find and list related parts, he can quickly navigate to the. Nav,.matrix and other relevant sections by searching ^lists.

Inheritance Tags

Using the object-oriented approach to CSS authoring, you can often find two parts of CSS closely related (one for the foundation, the first to expand) but two. We can use inheritance tags to establish a close connection between the original element and the inherited element. These are spelled in the comments as follows:

In the basic style of the element:

/** * Extend '. Foo ' in Theme.css * *. foo{}

In the extended style of the element:

/** * Extends '. Foo ' in Base.css * *. bar{}

In this way, we can build a close relationship between two pieces of code that are far apart.

Writing CSS

The previous chapters focused on how to plan for CSS, which are easy to quantify rules. This chapter will explore more theoretical things, and will explore our attitudes and methods.

Writing new components

When writing a new component, write the HTML part before you start working on the CSS. This allows you to accurately determine which CSS attributes can be inherited and avoid duplication of waste.

By writing the tags first, you can focus on data, content, and semantics, and then add the required class and CSS styles.

Object-oriented CSS

I write code in an object-oriented CSS way. I divide the components into structures (objects) and appearances (extensions). As in the following analysis (note here is not an example):

. room{}.room--kitchen{}.room--bedroom{}.room--bathroom{}

We have a lot of rooms in the house and they all have a common part: floors, ceilings, walls and doors. These shared parts can be placed in an abstract. room{} class. But we have other rooms that are different: a kitchen may have floor tiles, the bedroom may have carpets, the bathroom may not have windows but the bedroom will have, and the color of the walls of each room may be different. The idea of object-oriented CSS allows us to abstract the same parts into parts of the structure and then use a more specific class to extend these features and add special processing methods.

So, rather than writing a large number of different modules, you should try to find the repeating design patterns in these modules and abstract them out, write them as a reusable class, use them as a basis, and write other expansion modules in special situations.

When you want to write a new component, split it into structure and appearance. The most common class is used to ensure reusability when writing structural parts, and a more specific class is used to add design methods when writing appearances.

Layout

All components are not declared width, but are determined by their pro-element or grille system.

Be resolute not to declare heights. The height should be used only for things that have fixed dimensions, examples, and CSS sprites. The height should not be declared on elements such as P,ul,div. A more flexible line-height can be used if needed.

Grille systems should be understood as bookshelves. Is that they contain content, rather than loading them up as content, just as you set up the shelves and put things in. Splitting the grid system and other attributes of the element is more helpful in layout than declaring their size, and makes our front-end work more efficient.

You should not add any styles on the grille system, they are only for layout purposes. Add styles inside the grille system. Do not add box model-related attributes in any case in the grid system.

UI Dimensions

I set the UI size in a number of ways, including percentages, px,em,rem, and simply nothing.

Ideally, the grille system should be set in percent. As mentioned above, because I use the grid system to fix the column width and width of the page, I can ignore the element size.

I use REM to define the font size, and it is complemented by PX to be compatible with the old browser. This can combine the advantages of both EM and px. Here is a very nice Sass Mixin, assuming that you declare the base font size (Base-font-size) Elsewhere, you can use it to generate REM and the PX that is compatible with the old browser.

@mixin font-size ($font-size) {    font-size: $font-size +px;    Font-size: $font-size/$base-font-size +rem;}

I only use PX on elements that are already fixed size, including images and CSS sprites that have a fixed size of px.

Size

I'll define a class that is similar in principle to the grid system to declare the font size. These classes can be used for double heading ratings, please read pragmatic, practical font-sizing in CSS.

Shorthand

CSS shorthand should be used with caution.

Write like background:red; This kind of property is really very convenient, but you write the meaning is to declare background-image:none at the same time; Background-position:top left; Background-repeat:repeat; background-color:red;. Although most of the time this will not be a problem, but even if only one time the problem is worth considering to give up the shorthand. This should be changed to background-color:red;.

Similar, like the margin:0; Such statements are concise and refreshing, but they should be kept as clear as possible. If you just want to modify the bottom margin, you need to be specific, written margin-bottom:0;

At the same time, you need to declare the attributes to write clearly, do not because of shorthand and other attributes. For example, if you just want to get rid of the bottom margin, don't use a margin:0 that will also clear the other margins.

Shorthand is good, but it's also easy to abuse.

Id

Before we start working with selectors, keep this in mind:

Do not use the ID in CSS.

In the HTML ID can be used for JS and anchor point positioning, but in the CSS as long as the class, an ID also do not use.

The advantage of Class is reusability, and the degree of privacy is not high. The degree of privacy in a project can easily lead to problems, so it is especially important to reduce it. The ID is 255 times times more private than the class, so do not use it firmly in CSS.

Selector Selector

Be sure to keep the selector short and efficient.

Selectors that are positioned through the page element position are not ideal. For example, a selector such as sidebar H3 span{} is positioned too dependent on a relative position, and it can be difficult to maintain a style if you move the span outside of the H3 and sidebar.

A complex selection of structures can affect performance. The more complex the selector structure (e.g.. Sidebar H3 span is layer three,. Content UL p A is layer four), the greater the overhead of the browser.

Try to make the style do not depend on its positioning, try to keep the selector concise and clear.

As a whole, selectors should be as brief as possible (for example, with only one layer of structure), but the class name should not be too simplistic, for example. User-avatar is far better than. Usr-avt.

Keep in mind that class does not matter whether it is semantic or not, and should be concerned about their reasonableness. Instead of emphasizing the semantics of class names, focus on using names that are reasonable and not obsolete.

Over-decorated selectors

The overly-modified selectors are not ideal, as described in the previous article.

Overly-modified selectors are those that are like Div.promo. It is possible that you can only use. promo to get the same results. Of course you may occasionally need to use the element type to modify the class (for example, you write a. Error and want it to appear differently in different element types, for example. Error {color:red;} div.error {padding:14px;} ), but most of the time it should be avoided as much as possible.

Give an example of an overly modified selector, Ul.nav Li a{}. As mentioned above, we can delete ul immediately because we know. Nav is a list, and then we can see that a must be in Li, so we can rewrite this selector into. Nav a{}.

Selector performance

While browser performance is increasing and rendering CSS faster and faster, you should focus on efficiency. Using a short, nested selector without using the global selector (* {}) as the core selector avoids the problem of using the increasingly complex CSS3 new selector.

The core selector: The browser resolution selector is the right-to-left order, the right-most element is the element that the style takes effect, is the core selector.

Purpose of using CSS selectors

Rather than trying to use a selector to locate an element, a better way is to add a class directly to the element you want to add the style to. Let's take the example of a selector such as. Header ul {}.

Assuming that this UL is the site's full-site navigation, it is located in the header, and so far is the only UL element in the header: header ul{} can actually take effect, but this is not a good way, it is easy to obsolete, and very obscure. If we add another UL to the header, it will apply the style we wrote to the navigation section, even if we didn't think of the effect. This means that we either refactor a lot of code or write many new styles to the later UL to counteract the previous impact.

Your selector must match the reason you want to add a style to this element. Think about it, "I'm targeting this element because it's a. Header under the UL, or because it's my site navigation?" "This will determine how you should use the selector."

Make sure that your core selector is not a type selector, or an advanced object or an abstraction selector. For example, you must not find a selector such as. Sidebar ul {} or. footer. Media {} in our CSS.

Clear expression: Find the element you want to add the style to, not its pro element. Don't assume that HTML doesn't change. Use CSS to directly hit the elements you need, rather than opportunistic.

For full content Please refer to my article Shoot to kill; CSS Selector Intent

!important

Use!important only on the auxiliary class. It is also possible to use!important to elevate the priority, for example, if you want a rule to take effect, you can use. Error {color:red!important;}.

Avoid actively using!important. For example, do not use it to trickery when the CSS is very complex to write, to properly organize and refactor the previous parts, to keep the selector short and to avoid tension pile the effect with an ID.

Magic number and absolute positioning

Magic number refers to those numbers that "happen to have effect", and the use of magic numbers is very bad, because they are only palliative and lack of extensibility.

For example, using the. Dropdown-nav li:hover ul {top:37px;} moving the drop-down menu is far from a recipe, because the 37px here is a magic number. The reason why 37px comes into effect is that. Dropbox-nav happens to be high 37px.

At this point you should use. Dropdown-nav li:hover ul {top:100%;}, that is, no matter how high dropbox-down, this drop-down menu will move down 100%.

Whenever you want to put a number in the code, please think twice. If you can replace it with a keyword (for example, "pull from top to bottom"), or if there is a better solution, try to avoid top:100% the numbers directly.

Every single number you leave in CSS is a promise you make and you don't want to follow.

Conditional judgment

The style that is written specifically for IE is basically avoidable, and the only thing that needs to be done specifically for IE is to handle content that IE does not support (such as PNG).

In short, if you refactor the CSS, all layouts and box models do not have to be extra compatible with IE. That means you basically don't have <!--[if IE 7]> element{margin-left:-9px;} <! [endif]--> or similar compatible with IE's wording.

Debugging

If you want to solve the CSS problem, first remove the old code and then write the new one. If there is a problem with the old CSS, it is not possible to write the new code.

Delete the CSS and HTML parts until there are no bugs, and then you know where the problem is.

Sometimes writing a overflow:hidden or other code that hides the problem can have immediate effect, but overflow may not be a problem at all. So it's a cure, not a simple symptom.

CSS Preprocessor

I use Sass. Use should be flexible. Using Sass can make your CSS more powerful, but don't nest too complex. In Vanilla CSS, you can only use nesting where necessary, for example:

. Header{}.header. Site-nav{}.header. Site-nav li{}.header. Site-nav Li a{}

This kind of writing is completely useless in the normal CSS. The following is a bad Sass notation:

. header{    . site-nav{        li{            a{}        }    }

If you use Sass, try to write like this:

. header{}.site-nav{    li{}    a{}}

Original: General CSS notes, advice and guidelines

CSS Authoring Guidelines and recommendations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.