Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the coding specifications and optimization suggestions that should be paid attention to in CSS code?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

CSS code needs to pay attention to what are the writing specifications and optimization recommendations, in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Separation of structure, style and behavior

Try to make sure that documents and templates contain only HTML structures, styles are put into stylesheets, and behaviors are put into scripts.

Indent

Unify the indentation of two spaces (in short, indent and unify), do not use Tab or Tab, space mashup.

File coding

Use UTF-8 encoding without BOM.

Specify the encoding in HTML

You do not need to use @ charset to specify the encoding of the stylesheet, which defaults to UTF-8

All use lowercase letters

CSS Code copies content to the clipboard

span"Google"/span

Home

/ * Recommended * /

Color: # e5e5e5

/ * Not recommended * /

Color: # E5E5E5

Omit the URL protocol part of the outer chain resources

Omit the http / https protocol in the outer link resources (pictures and other media resources) URL to make URL a relative address, avoid Mixed Content problems, and reduce the number of file bytes.

URL for other protocols (ftp, etc.) is not omitted.

CSS Code copies content to the clipboard

/ * Recommended * /

.example {

Background: url (/ / www.google.com/images/example)

}

/ * Not recommended * /

.example {

Background: url (http://www.google.com/images/example);

}

CSS comment

Component blocks and subcomponent blocks and declaration blocks are separated by a blank line, and subcomponent blocks are separated by three blank lines

CSS Code copies content to the clipboard

/ * =

Component block

=

/ * Sub-component block

=

.selector {

Padding: 15px

Margin-bottom: 15px

}

/ * Sub-component block

=

. selector-secondary {

Display: block; / * comments * /

}

. selector-three {

Display: span

}

Code organization

Organize code snippets by component

Develop consistent annotation specifications

Component blocks and subcomponent blocks and declaration blocks are separated by a blank line, and subcomponent blocks are separated by three blank lines

If multiple CSS files are used, split them as components rather than pages, because the pages will be reorganized and the components will only be moved

Good comments are very important. Set aside time to describe how components (component) work, their limitations, and how they are built. Don't let the rest of your team guess the purpose of an uncommon or obscure piece of code.

Tip: through the configuration editor, you can provide shortcuts to output agreed comment patterns.

CSS Code copies content to the clipboard

/ * =

Component block

=

/ * Sub-component block

=

.selector {

Padding: 15px

Margin-bottom: 15px

}

/ * Sub-component block

=

. selector-secondary {

Display: block; / * comments * /

}

. selector-three {

Display: span

}

Class and ID

Use semantic, generic naming methods

Use hyphens-as ID, Class name delimiters, no hump naming and underscores

Avoid too many levels of selector nesting, as far as possible less than 3 levels

Avoid the superimposed use of selector and Class and ID

For performance reasons, avoid the use of element selectors overlaying Class and ID when not necessary.

The mixed use of element selectors with ID and Class also violates the principle of separation of concerns. If the HTML tag is modified, it is necessary to modify the CSS code, which is not conducive to later maintenance.

CSS Code copies content to the clipboard

/ * Not recommended * /

.red {}

.box _ green {}

.page .header .login # username input {}

Ul#example {}

/ * Recommended * /

# nav {}

. box-video {}

# username input {}

# example {}

Declare block format

When selector grouping, keep independent selector occupies a row

Add a space before the left parenthesis {of the declaration block

The right parenthesis} of the declaration block should be on a separate line

Add a space after the: in the declaration statement

The declaration statement should end with a semicolon

Attribute values usually separated by commas, with a space added after each comma

Values in parentheses rgb (), rgba (), hsl (), hsla () or rect (), separated by commas, but without adding a space after the comma

For attribute values or color parameters, omit the 0 before the decimal less than 1 (for example, .5 instead of 0.5shareholder .5px instead of-0.5px)

Hexadecimal values should be all lowercase and as short as possible, for example, # fff instead of # ffffff

Avoid specifying a unit for a value of 0, for example, using margin: 0; instead of margin: 0px

CSS Code copies content to the clipboard

/ * Not recommended * /

.selector, .selector-secondary, .selector [type=text] {

Padding:15px

Margin:0px 0px 15px

Background-color:rgba (0,0,0,0.5)

Box-shadow:0px 1px 2px # CCC,inset 0 1px 0 # FFFFFF

}

/ * Recommended * /

.selector

. selector-secondary

.selector [type= "text"] {

Padding: 15px

Margin-bottom: 15px

Background-color: rgba (0pd0j0j0pl .5)

Box-shadow: 0 1px 2px # ccc, inset 0 1px 0 # fff

}

Declaration order

The related attributes should be a group, and the recommended style writing order

Positioning

Box model

Typographic

Visual

Positioning comes first because it removes elements from a normal document stream and also overrides styles related to the box model (box model). The box model determines the size and location of the components, so it ranks second.

The other properties only affect the inside of the component or do not affect the first two sets of properties, so they come last.

CSS Code copies content to the clipboard

. declaration-order {

/ * Positioning * /

Position: absolute

Top: 0

Rightright: 0

Bottombottom: 0

Left: 0

Z-index: 100

/ * Box model * /

Display: block

Box-sizing: border-box

Width: 100px

Height: 100px

Padding: 10px

Border: 1px solid # e5e5e5

Border-radius: 3px

Margin: 10px

Float: rightright

Overflow: hidden

/ * Typographic * /

Font: normal 13px "Helvetica Neue", sans-serif

Line-height: 1.5

Text-align: center

/ * Visual * /

Background-color: # f5f5f5

Color: # fff

Opacity:. 8

/ * Other * /

Cursor: pointer

}

Quotation marks use

Url (), attribute selectors, and attribute values use double quotation marks. Refer to Is quoting the value of url () really necessary?

CSS Code copies content to the clipboard

/ * Not recommended * /

@ import url (/ / www.google.com/css/maia.css)

Html {

Font-family: 'open sans', arial, sans-serif

}

/ * Recommended * /

@ import url ("/ / www.google.com/css/maia.css")

Html {

Font-family: "open sans", arial, sans-serif

}

.selector [type= "text"] {

}

Location of Media Inquiry (Media query)

Place media queries near as relevant rules as possible. Do not package them in a single style file or at the bottom of the document. If you separate them, they will only be forgotten in the future.

CSS Code copies content to the clipboard

.element {...}

. element-avatar {...}

. element-selected {...}

@ media (max-width: 768px) {

.element {...}

. element-avatar {...}

. element-selected {...}

}

Do not use @ import

By comparison, @ import is much slower, not only increasing the number of additional requests, but also causing unexpected problems.

Alternative:

Use multiple elements

Compile multiple CSS files into one file through a Sass or Less-like CSS preprocessor

Other CSS file merge tools

Refer to don't use @ import

Style order of links:

CSS Code copies content to the clipboard

A:link-> a:visited-> a:hover-> a:active (LoVeHAte)

No need to add browser vendor prefix

Use Autoprefixer to automatically add browser manufacturer prefixes, writing CSS without adding browser prefixes, directly using the standard CSS writing.

Through Can I use, Autoprefixer adds browser vendor prefixes to the corresponding CSS code according to compatibility requirements.

Module organization

Any CSS code with more than 1000 lines of code, you have experienced this experience:

What exactly does this class mean?

Where is this class used?

If I create a xxoo class, will it cause conflict?

The goal of Reasonable System for CSS Stylesheet Structure is to solve the above problems. It is not a framework, but a specification that allows you to build more robust and maintainable CSS code.

Components (component)

From the perspective of Components, consider the modules of the website as an independent Components.

Naming components (component naming)

Components is named after at least two words, through-separation, for example:

Like button (.like-button)

Search box (.search-form)

Article card (.article-card)

Elements (element)

Elements is an element in Components

Naming elements (element naming)

The class name of Elements should be as small as one word as possible.

CSS Code copies content to the clipboard

. search-form {

> .field {/ *... * /}

> .action {/ *... * /}

}

On multiple words (multiple words)

If you need two or more words to express the Elements class name, you should not use underscore and underscore concatenation, but should connect directly.

CSS Code copies content to the clipboard

. profile-box {

> .firstname {/ *... * /}

> .lastname {/ *... * /}

> .avatar {/ *... * /}

}

Avoid tag selectors (avoid tag selector)

Use classnames whenever possible. There is no problem with the use of the tag selector, but its performance is slightly weaker and the meaning is not clear.

CSS Code copies content to the clipboard

. article-card {

> h4 {/ * ✗ avoid * /}

> .name {/ * ✓ better * /}

}

Variants (variant)

Both Components and Elements may have Variants.

Naming variants (variant naming)

The classname of Variants should be prefixed with an underscore-

CSS Code copies content to the clipboard

. like-button {

&.-wide {/ *... /}

&.-short {/ *... /}

&.-disabled {/ *... /}

}

Element variants (element variant)

CSS Code copies content to the clipboard

. shopping-card {

> .title {/ *... * /}

> .title.-small {/ *... * /}

}

Dash prefixes (dashed prefix)

Why use the dash as the prefix for the variant?

It can avoid ambiguity and Elements

CSS class can only start with a word and _ or-

Middle underscore is easier to output than underscore.

Layout (layout)

Avoid positioning properties (avoid positioning attributes)

Components should be reusable in different contexts, so avoid setting the following properties:

Positioning (position, top, left, right, bottom)

Floats (float, clear)

Margins (margin)

Dimensions (width, height) *

Fixed dimensions (fixed size)

Elements such as avatar and logos should be set to a fixed size (width, height...).

Define positioning in parents (set positioning in the parent element)

If you need to locate a component, you should handle it in the context (parent element) of the component. For example, in the following example, widths and floats are applied to list component (.article-list) rather than component (.article-card) itself.

CSS Code copies content to the clipboard

. article-list {

& {

@ include clearfix

}

> .article-card {

Width: 33.3%

Float: left

}

}

. article-card {

& {/ *. * /}

> .image {/ *... * /}

> .title {/ *... * /}

> .category {/ *... * /}

}

Avoid over-nesting (avoid overnesting)

When multiple nesting occurs, it is easy to get out of control, so no more than one nesting should be maintained.

CSS Code copies content to the clipboard

/ * ✗ Avoid: 3 levels of nesting * /

. image-frame {

> .description {

/ *. /

> .icon {

/ *. /

}

}

}

/ * ✓ Better: 2 levels * /

. image-frame {

> .description {/ *... * /}

> .description > .icon {/ *... * /}

}

Apprehensions (concerns)

Underlining-it's a terrible thing: you can use it selectively, as long as you keep Components, Elements, and Variants in mind.

Sometimes I can't think of two words: some components do use one word to express meaning, such as aleter. But you can actually use suffixes to make them more conscious.

For example, block-level elements:

. alert-box

. alert-card

. alert-block

Or inline-level elements

. link-button

. link-span

Terminologies (terminology)

The concept of RSCSS is similar to that of other CSS module organization systems

RSCSSBEMSMACSSComponentBlockModuleElementElement?Layout?LayoutVariantModifierTheme & State

Summary (summary)

Think about it from the perspective of Components and name it after two words (.screenshot-image)

Elements in Components, named after one word (.blog-post .title)

Variants with an underscore-as a prefix (.shop-banner.-with-icon)

Components can be nested with each other

Remember, you can make things easier by inheriting.

LESS specification

Code organization

The code is organized in the following order:

@ import

Variable declaration

Style declaration

CSS Code copies content to the clipboard

@ import "mixins/size.less"

@ default-text-color: # 333

.page {

Width: 960px

Margin: 0 auto

}

@ import statement

The text referenced by the @ import statement needs to be written in a pair of quotation marks, and the .less suffix cannot be omitted. Quotation marks can be used in both 'and', but they are unified within the same project.

CSS Code copies content to the clipboard

/ * Not recommended * /

@ import "mixins/size"

@ import 'mixins/grid.less'

/ * Recommended * /

@ import "mixins/size.less"

@ import "mixins/grid.less"

Blend in (Mixin)

When defining a mixin, if the mixin name is not a required className, you must add parentheses, otherwise it will be output to the CSS even if it is not called.

If you are mixing a mixin that does not output itself, you need to add parentheses after the mixin (even if no arguments are passed) to distinguish whether this is a className.

CSS Code copies content to the clipboard

/ * Not recommended * /

. big-text {

Font-size: 2em

}

H4 {

. big-text

.clearfix

}

/ * Recommended * /

.big-text () {

Font-size: 2em

}

H4 {

.big-text (); / * 1 * /

.clearfix (); / * 2 * /

}

Avoid too many levels of nesting

Limit the nesting depth to level 2. For more than 3 levels of nesting, re-evaluate. This avoids overly detailed CSS selectors.

Avoid a large number of nested rules. When readability is affected, interrupt it. It is recommended to avoid more than 20 lines of nested rules.

String interpolation

Variables can be embedded in strings in ways like ruby and php, with structures like @ {name}: @ base-url: "http://assets.fnord.com"; background-image: url (" @ {base-url} / images/bg.png ")

Performance optimization

Carefully choose the style with high consumption

High-cost attributes require a large number of calculations by the browser before drawing:

Box-shadows

Border-radius

Transparency

Transforms

CSS filters (performance killer)

Avoid excessive rearrangement

When a rearrangement occurs, the browser needs to recalculate the layout location and size for more details.

Common rearrangement elements:

Width

Height

Padding

Margin

Display

Border-width

Position

Top

Left

Right

Bottom

Font-size

Float

Text-align

Overflow-y

Font-weight

Overflow

Font-family

Line-height

Vertical-align

Clear

White-space

Min-height

Correctly use the properties of Display

The Display attribute will affect the rendering of the page, so please use it reasonably.

Display: width, height, margin, padding and float should no longer be used after inline

Display: float should no longer be used after inline-block

Display: vertical-align should no longer be used after block

Display: margin or float should no longer be used after table-*

Do not abuse Float

Float has a large amount of computation when rendering, so try to reduce the use of it.

Animation performance optimization

The realization principle of animation is to make use of the "visual temporary" phenomenon of the human eye to continuously play several still pictures in a short period of time, so that the naked eye can mistakenly think that the picture is "moving" because of the visual residual image.

The basic concepts of animation:

Frame: in the process of animation, each still picture is a "frame"

Frame rate: the number of still pictures played per second, in fps (Frame per second)

Frame length: the dwell time of each still picture, usually in ms (milliseconds)

Frame skipping (frame drop / frame drop): in an animation with a fixed frame rate, the duration of a frame is longer than the average frame length, resulting in the subsequent frames being squeezed and lost.

In general, the rendering refresh rate of browsers is 60 fps, so in web pages, animations with a frame rate of 50-60 fps will be quite smooth and comfortable.

If you are using javaScript-based animation, try to use requestAnimationFrame. Avoid using setTimeout,setInterval.

Avoid changing the style of each frame through something like jQuery animate ()-style, and use CSS to declare that the animation will be better optimized for the browser.

Using translate instead of absolute positioning will result in better fps and smoother animation.

Make more use of hardware capabilities, such as enabling GPU acceleration through 3D deformation

In general, in Chrome, 3D or perspective transformation (perspective transform) CSS attributes and CSS animation of opacity will create new layers. Under the optimization of hardware-accelerated rendering channel, GPU performs composite operation (Compesite Layers) after 3D deformation and other operations, so as to avoid triggering large area redrawing and rearrangement in the browser.

Note: 3D deformation consumes more memory and power consumption.

Using translate3d to move 500px to the right is significantly better than using left directly:

CSS Code copies content to the clipboard

.ball-1 {

Transition:-webkit-transform .5s ease

-webkit-transform: translate3d (0,0,0)

}

. ball-1.slidein {

-webkit-transform: translate3d (500px, 0,0)

}

.ball-2 {

Transition: left .5s ease; left:0

}

. ball-2.slidein {

Left:500px

}

Improve the performance of CSS selector

The performance impact of CSS selectors comes from the time it takes for browsers to match selectors and document elements, so the principle for optimizing selectors is to avoid using selectors that consume more matching time. Before that, we need to understand the mechanism of CSS selector matching, such as sub-selector rules:

CSS Code copies content to the clipboard

# header > a {font-weight:blod;}

Most of us are in the habit of reading from left to right, and we habitually set browsers to match rules from left to right, speculating that this rule is not expensive.

We will assume that the browser works in such a way that it looks for an element whose id is header, and then applies the style rules to the an element in the immediate child element. We know that there is only one element in the document whose id is header, and it has only a few child nodes of element a, so this CSS selector should be quite efficient.

In fact, on the contrary, the CSS selector matches rules from right to left. After understanding this mechanism, the matching overhead of the seemingly efficient selector in the example is very high in practice, and the browser must traverse all the an elements in the page and determine whether the id of its parent element is header.

It is more expensive to change the child selector of the example to the descendant selector, traversing all the an elements in the page and traversing its superiors to the root node.

CSS Code copies content to the clipboard

# header a {font-weight:blod;}

After understanding the mechanism of CSS selector matching from right to left, it is understood that as long as there are other selectors to the left of the current selector, the style system will continue to move to the left until a selector that matches the rule is found, or exits because of a mismatch. We call the rightmost selector a key selector.

1. Avoid using universal selectors

CSS Code copies content to the clipboard

/ * Not recommended * /

.content * {color: red;}

After matching all the elements in the document, the browser matches the elements whose class is content up to the root node of the document. Therefore, the matching overhead is very high, so you should avoid using a key selector that is a wildcard selector.

two。 Avoid using tags or class selectors to restrict id selectors

CSS Code copies content to the clipboard

/ * Not recommended * /

Button#backButton {... }

/ * Recommended * /

# newMenuIcon {... }

3. Avoid using tags to restrict class selectors

CSS Code copies content to the clipboard

/ * Not recommended * /

Treecell.indented {... }

/ * Recommended * /

. treecell-indented {... }

/ * Much to recommended * /

. hierarchy-deep {... }

4. Avoid using multi-layer tag selectors. Use class selector replacement to reduce css lookup

CSS Code copies content to the clipboard

/ * Not recommended * /

Treeitem [mailfolder= "true"] > treerow > treecell {... }

/ * Recommended * /

. treecell-mailfolder {... }

5. Avoid using sub-selectors

CSS Code copies content to the clipboard

/ * Not recommended * /

Treehead treerow treecell {... }

/ * Recommended * /

Treehead > treerow > treecell {… }

/ * Much to recommended * /

. treecell-header {... }

6. Use inheritance

CSS Code copies content to the clipboard

/ * Not recommended * /

# bookmarkMenuItem > .menu-left {list-style-image: url (blah)}

/ * Recommended * /

# bookmarkMenuItem {list-style-image: url (blah)}

On the CSS code need to pay attention to the preparation of specifications and optimization suggestions to share the answers to what questions here, I hope the above content can be of some help to you, if you still have a lot of doubts to solve, you can follow the industry information channel to learn more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report