CSS writing guidelines and suggestions, CSS Writing Guidelines

Source: Internet
Author: User
Tags all definition code tag css preprocessor

CSS writing guidelines and suggestions, CSS Writing Guidelines

When participating in a large, long, and attended project, it is extremely important for all developers to follow the following rules:

  • Keep CSS easy to maintain
  • Keep code clear and easy to understand
  • Keep CSS extensible

To achieve this goal, we need to adopt many methods.

The first part of this document will discuss the syntax, format, and analysis of the CSS structure. The second part will focus on the methodology, thinking framework, and the views on writing and planning CSS.

CSS document analysis

No matter what documents are written, we should maintain a uniform style, including unified comments, unified syntaxes, and unified naming rules.

General

Control the row width below 80 bytes. Gradient-related syntaxes and URLs in comments can be counted as exceptions. After all, we can't do anything about this part.

I tend to use four spaces instead of Tab indentation and split the Declaration into multiple rows.

Single file and multi-File

Some people like to write all the content in a file, and I began to split the style into multiple small files after migrating to Sass. This is a good practice. Whatever you choose, the following rules will apply, and you will not encounter any problems if you follow these rules. The difference between the two statements is that directories and block titles:

Directory

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

/*------------------------------------*\    $CONTENTS\*------------------------------------*//** * CONTENTS............You’re reading it! * RESET...............Set our reset defaults * FONT-FACE...........Import brand font files */

This directory tells other developers what content this file contains. Each item in this directory is the same as its corresponding block title.

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

Block title

The Directory should correspond to the block title. As follows:

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

Block title prefix $ allows us to use the [Cmd | Ctrl] + F command to limit the search range to the block title.

If you are maintaining a large file, five lines are left blank between blocks, as shown below:

/*------------------------------------*\    $RESET\*------------------------------------*/[Ourresetstyles]/*------------------------------------*\    $FONT-FACE\*------------------------------------*/

When a large file is quickly flipped, these large blocks of blank files help distinguish blocks.

If you are maintaining multiple sets of CSS connected with include, you can add titles to each file header without such blank lines.

Code sequence

Try to write rules in a specific order, which will make sure that you make full use of the meaning of the first C in CSS: cascade, cascade.

A well-planned CSS should be arranged as follows:

In this way, when you write CSS in sequence, each block can automatically inherit the attributes of the block before it. In this way, we can reduce the amount of code offset, reduce some special problems, and form a more ideal CSS structure.

For more information, we strongly recommend Jonathan Snook's SMACSS.

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

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

  • The class name is connected by a hyphen (-), except for the BEM naming method mentioned below;
  • Indent with 4 spaces;
  • Split the statement into multiple rows;
  • Statements are sorted in relevance order, not in alphabetical order;
  • The declaration with a prefix is indented to align its value;
  • Indent the style set to reflect the DOM;
  • Retain the semicolon at the end of the last statement.

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 element of. widget, because the style set of the former is more indented than that of the latter. In this way, developers can quickly obtain such important information when reading the Code through indentation.

We can also find that the declaration of. widget-heading is arranged according to its relevance:. widget-heading is a line element, so we first add the style Declaration related to the font, followed by other.

The following is an example of not sharding into multiple rows:

.t10    { width:10% }.t20    { width:20% }.t25    { width:25% }       /* 1/4 */.t30    { width:30% }.t33    { width:33.333% }   /* 1/3 */.t40    { width:40% }.t50    { width:50% }       /* 1/2 */.t60    { width:60% }.t66    { width:66.666% }   /* 2/3 */.t70    { width:70% }.t75    { width:75% }       /* 3/4*/.t80    { width:80% }.t90    { width:90% }

In this example (inuit.css's table grid system), placing CSS in a row makes the code more compact.

Naming rules

In general, I use a hyphen (-) to connect to the class name (for example. foo-bar instead. foo_bar or. fooBar), but in some specific cases, I will use the BEM (Block, Element, Modifier) naming method.

BEM naming can make the selector more standardized, clearer, and more semantic.

The naming method follows the following format:

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

Where:

  • . Block represents a basic abstract element;
  • . Block _ element indicates a child element that constitutes a. block;
  • . Block -- modifier indicates a different status or version of. block.

For example:

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

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

In this way, the selector namespace can be defined based on the parent element and the functions of the selector can be conveyed. For example, the selector is a child element (__) or the different states of the parent element (--).

Therefore,. page-wrapper is an independent selector. This is a naming convention, because it is not a child element or other State of other elements; however. widget-heading is associated with other objects. It should be. child element of the widget, so we should rename it. widget _ heading.

Although BEM naming is not very nice and lengthy, it allows us to quickly learn the relationship between the functions and elements of an element by name. At the same time, the duplicates in the BEM syntax are very beneficial to the gzip compression algorithm.

Whether you use the BEM naming method or not, you should ensure that the class is properly named, to ensure that there are not many or many words, and that the element names are abstracted to improve reusability (for example. ui-list ,. media ). The sub-element name should be as accurate as possible (for example,. user-avatar-link ). Don't worry about the number or length of class names, because well-written code gzip can also be effectively compressed.

Class in HTML

To ensure ease of coding, two spaces are used to separate class names in HTML tags. For example:

<div class="foo--bar  bar__baz">

The added space should make it easier to read and locate multiple classes.

JavaScript hook

Do not use a class that marks the CSS style as a JavaScript hook. Mixing JS behavior and style together cannot process them separately.

If you want to bind JS with some tags, write a class dedicated to JS. In short, it is to define a namespace prefix. js-such as. js-toggle and. js-drag-and-drop. This means that we can bind JS and CSS through the class at the same time, without the trouble caused by conflicts.

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

The above mark has two classes. You can use one of them to add a style to the sortable column and the other to add the sorting function.

I18n

Although I (the original author of the CSS Guideline document Harry Roberts) are British and I have always spelled color rather than color, I think it is better to use American spelling in CSS to pursue unification. CSS and most other languages are written in American spelling, So if you write color: red in. color-picker {}, there is no uniformity. I previously proposed two methods at the same time, for example:

.color-picker,.colour-picker{}

However, I recently participated in a large-scale Sass Project, which contains many color variables (such as $ brand-color and $ highlight-color ), it is really hard to maintain two spell methods for each variable. It also takes twice the workload to search for and replace the variable.

To ensure consistency, you can name all the classes and variables in the usual spelling of the projects you participate in.

Note

Note:

/*** This is a docBlock style comment ** This is a longer description of the comment, describing the code in more * detail. we limit these lines to a maximum of 80 characters in length. ** We can have markup in the comments, and are encouraged to do so: * <div class = "foo"> <p> Lorem </p> </div> ** We do not prefix lines of code with an asterisk as to do so wowould inhibit * copy and paste. *//*** This is a DocBlock-style annotation. ** At the beginning, the comments with more details and longer length are described. Of course, we need to keep the row width within 80 bytes. ** We can embed HTML tags in annotations, and this is also a good method: * <div class = "foo"> <p> Lorem </p> </div> ** if it is an embedded annotation mark, no star number is added before it, to avoid being copied. */

The Code should be described as detailed as possible in comments, because the clear and easy-to-understand content may not be the case for others. For each part of the code, you need to write comments to explain them in detail.

Extended usage of annotations

Annotations have many advanced usage methods, such:

  • Quasi-modifier selector (Quasi-qualified selectors)
  • Code tag
  • Inheritance tag
Quasi-modifier selector (Quasi-qualified selectors)

You should avoid over-modifying the selector. For example, if you can write. nav {}, try not to write ul. nav {}. Modifying the selector excessively affects the performance, the class reusability, and the private degree of the selector. These are all things you should avoid.

However, sometimes you may want to tell other developers the scope of use of the class. Taking. product-page as an example, this class looks like a root container, which may be an html or body element, but it cannot be determined only by. product-page.

We can add a quasi-modifier before the selector (comment out the previous type selector) to describe the scope of the planned class:

/*html*/.product-page{}

In this way, we can accurately understand the scope of the class without affecting reusability.

Other examples include:

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

In this way, we can know the scope of the class without affecting the code privacy.

Code tag

If you have written a new set of styles, you can add tags on them, for example:

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

These tags allow other developers to quickly find the relevant code. If a developer needs to search for list-related parts, he can search ^ lists to quickly locate. nav,. matrix, and other related parts.

Inheritance tag

If you use object-oriented thinking for CSS writing, you can often find two parts of CSS closely related (one is the basis, and the other is expansion), but they are divided into two parts. We can use the inheritance tag to establish a close relationship between the original element and the inherited element. These annotations are written 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 establish a close relationship between the two codes that are far apart.

Write CSS

The previous sections mainly discuss how to plan CSS, which are easy to quantify rules. This chapter will discuss more theoretical things and our attitudes and methods.

Write new components

When writing new components, you must write the HTML section before proceeding with CSS processing. This allows you to accurately determine which CSS attributes can be inherited to avoid repeated waste.

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 the form of object-oriented CSS. I divide components into structures (objects) and appearances (extensions ). As shown in the following analysis (note that this is not an example ):

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

We have many rooms in the room, all of which share the same part: Floor, ceiling, walls and doors. The shared parts can be put in an abstract. room {} class. However, we also have other distinctive rooms: A kitchen may have floor tiles, a bedroom may have carpets, a bathroom may have no windows, but a bedroom may have different wall colors. The idea of targeting CSS allows us to abstract the same part to form a structural part, and then use a more specific class to expand these features and add special processing methods.

Therefore, instead of writing a large number of different modules, we should try to find out the repeated design patterns in these modules and abstract them into a reusable class, use it as the basis and write other extended modules.

When you want to write a new component, split it into structure and appearance. When writing the structure, use the most common class to ensure reusability. When writing the appearance, use a more specific class to add the design method.

Layout

Do not declare the width of all components, which is determined by the parent element or grid system.

Never declare height. The height should only be used for fixed dimensions, such as slice and CSS Sprite. Height should not be declared on elements such as p, ul, and div. If needed, you can use a more flexible line-height.

The grid system should be understood as a shelf. They hold the content, rather than loading it as the content, just as you first set up a shelf and then put it in. Compared with declaring their sizes, splitting the grid system and other attributes of the elements is more helpful for layout and makes our front-end work more efficient.

You should not add any styles to the grid system. They are only used for layout. Add a style inside the grid system. In the grid system, do not add the box model attributes in any case.

UI size

I use many methods to set the UI size, including percentage, px, em, rem, and nothing else.

Ideally, the grid system should be set in percentage. As mentioned above, because I use a grid system to fix the Bar Width and page width, I can ignore the element size.

I use rem to define the font size and px to be compatible with old browsers. This can have both em and px advantages. The following is a pretty Sass Mixin. If you declare a base-font-size elsewhere, you can use it to generate rem and px 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 fixed-size elements, including images and CSS Sprite with fixed-size pixels.

Font Size

I will define some classes similar to the grid system principle to declare the font size. These classes can be used for dual title classification. For more information, see Pragmatic and practical font-sizing in CSS.

Shorthand

CSS abbreviations should be used with caution.

Writing attributes such as background: red is really easy, but what you write here actually means declaring background-image: none; background-position: top left; background-repeat: repeat ;. Although most of the time this will not cause any problem, even if only one problem occurs, it is worth considering whether to give up the shorthand. This should be changed to background-color: red ;.

Similarly, statements like margin: 0; are concise and refreshing, but we should try to make it clear. If you only want to modify the bottom edge margin, you need to write it as margin-bottom: 0 ;.

At the same time, you need to clearly define the attributes you need to declare, and do not apply other attributes because of shorthand. For example, if you only want to remove the margin at the bottom, do not use the margin: 0 that will also remove other margins.

Although the short form is good, it is also easy to abuse.

ID

Remember this sentence before we start to process the selector:

Do not use ID in CSS.

In HTML, ID can be used for JS and anchor locating. However, you only need to use class in CSS, and an ID is not used.

The advantage of Class is reusability, and the private level is not high. In projects, the private level is very easy to cause problems, so it is especially important to reduce it. The private degree of the ID is 255 times that of the class, so do not use it in CSS.

Selector

Make sure that the selector is short and efficient.

The selector located by PAGE element location is not ideal. For example, a selector like. sidebar h3 span {} is positioned to be too dependent on the relative position. It is difficult to maintain the style when moving the span outside h3 and sidebar.

A complex selector may affect the performance. The more complex the selector structure (for example, the. sidebar h3 span is three layers, and the. content ul p a is four layers), the larger the browser overhead is.

Try to make the style independent of its positioning, and keep the selector concise and clear as much as possible.

As a whole, the selector should be as short as possible (for example, there is only one layer of structure), but the class name should not be too simple. For example,. user-avatar is far better than. usr-avt.

Remember: class doesn't matter whether it is semantic; you should pay attention to whether they are reasonable. Do not emphasize that the class name must conform to the semantics, but pay attention to the use of reasonable and non-outdated names.

Modifier Selector

As mentioned above, the excessively modified selector is not ideal.

An over-modified selector is like div. promo. It is very likely that you only use. promo to achieve the same effect. Of course, you may occasionally need to use the element type to modify the class (for example, if you write. error and want it to display different effects in different element types, for example. error {color: red;} div. error {padding: 14px;}), but it should be avoided most of the time.

Here is another example of an excessively modified selector, ul. nav li {}. As mentioned above, we can immediately delete ul because we know. nav is a list, and then we can find that a must be in li, so we can rewrite this selector. nav {}.

Selector Performance

Although the browser performance is improving and CSS rendering is faster and faster, you should pay attention to the efficiency. Use a short, non-nested selector instead of a global selector (* {}) as the core selector to avoid the problem of using the increasingly complex CSS3 new selector.

Core selector: the browser resolution selector is in the order from right to left. the rightmost element is the element that the style takes effect and is the core selector.

Purpose of using the CSS Selector

A better way is to add a class directly to the element you want to add a style to than to use the selector to locate an element. Take a selector like. header ul {} as an example.

Assume that ul is the full-site navigation of the website. It is located in the header and is currently the only ul element in the header .. The header ul {} does take effect, but this is not a good method. It is very outdated and obscure. If we add another ul in the header, it will apply the style we wrote to this navigation part, even if we didn't imagine this effect. This means we have to refactor a lot of code, or write a lot of new styles for ul to offset the previous impact.

Your selector must match the reason you want to add a style to this element. Think about it. "I have located this element because it is ul under. header, or because it is my website navigation ?」 This will determine how you should use the selector.

Make sure that your core selector is neither a type selector nor an advanced object or abstract selector. For example, you cannot find a selector such as. sidebar ul {} Or. footer. media {} in our CSS.

Clear expression: directly find the element you want to add a style, rather than its parent element. Do not assume that HTML will not change. Use CSS to directly hit the elements you need, rather than opportunistic.

For more information, see Shoot to kill. CSS selector intent.

! Important

It is only used in the class that plays an auxiliary role! Important. Yes! Important can also improve the priority. For example, if you want to keep a rule effective, you can use. error {color: red! Important ;}.

Avoid active use! Important. For example, when CSS is very complex, do not use it to make it happen. sort out and reconstruct the previous part, keep the selector short, and avoid using ID to group the effect.

Magic number and absolute positioning

Magic Number refers to the "coincidentally effective" numbers. It is very difficult to use Magic numbers because they are only temporary and lack scalability.

For example, using. dropdown-nav li: hover ul {top: 37px;} to move the drop-down menu is far from a good idea, because 37px here is a magic number. The reason why 37px takes effect is that. dropbox-nav happens to be 37px High.

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

Every time you put a number in your code, think twice. If you can replace it with a keyword (for example, top: 100% means "pull from top to bottom") or have a better solution, try to avoid direct numbers.

Every number you leave in CSS is a promise you make rather than follow.

Condition judgment

Styles written specifically for IE are basically avoided. The only thing that needs to be specially designed for IE is to process content not supported by IE (such as PNG ).

In short, if you refactor CSS, all layout and box models do not need to be compatible with IE. That is to say, you basically don't need to <! -- [If IE 7]> element {margin-left:-9px ;}<! [Endif] --> or similar method compatible with IE.

Debugging

If you want to solve the CSS problem, remove the old code and then write a new one. If there is a problem with the old CSS, writing new code won't solve it.

Delete the CSS code and HTML part until there is no BUG, and then you will know where the problem is.

Sometimes writing an overflow: Den den or other code that can hide the problem is indeed very effective, but it may be okay in terms of overflow. Therefore, the root cause must be the root cause, rather than the root cause.

CSS Preprocessor

I use Sass. It should be used flexibly. Sass can make your CSS more powerful, but it should not be nested too complicated. In Vanilla CSS, you only need to use nesting where necessary. For example:

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

This method is completely unavailable in general CSS. The following is a poor Sass Syntax:

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

If you use Sass, try to write as follows:

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

Original article: General CSS notes, advice and guidelines

 


Q: What are the standards for CSS style sheet writing?

When CSS is used in XHTML, the element names defined in CSS are case sensitive. To avoid this error, we recommend that all definition names be in lower case.

The values of class and id are also case-sensitive in HTML and XHTML. If you must write them in combination with uppercase and lowercase, make sure that your CSS definition is consistent with the tags in XHTML.

You can use single quotes and double quotes, but do not mix them. For example, "100' cannot be used.

How can I make html and css code more standard?

Hello, Questioner:
-----> Reference document: www.cnblogs.com/...1.html
Sun Cheng [authoritative expert]

Related Article

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.