Write CSS in a more sensible way
- Disciplined code promotes teamwork,
- The canonical code can be reduced
bug
To deal with, - Regular code can reduce maintenance costs,
- Normative code facilitates code review,
- Getting into the habit of code specification helps programmers grow.
1 introduction
2 Code Style
- 2.1 file
- 2.2 the indentation
- 2.3 the blank space
- 2.4 length
- 2.5 the selector
- 2.6 attributes
Three general
- 3.1 the selector
- 3.2 Attribute Abbreviations
- 3.3 Writing sequence of attributes
- 3.4 Clearing floats
- 3.5 !important
- 3.6 z – index
4 values and units
- 4.1 the text
- 4.2 numerical
- 4.3 the url ()
- 4.4 the length of the
- 4.5 color
- 4.6 the 2 d position
5 Text Formatting
- 5.1 font family
- 5.2 the shop name
- 5.3 Font Style
- 5.4 the word again
- 5.5 line height
6 transformation and animation
7 reactive
8 compatibility
- 8.1 Attribute Prefix
- 8.2 Hack
- 8.3 Expression
1 introduction
As the description language of web page style, CSS has been widely used in Baidu. The goal of this document is to make CSS code style consistent, easy to understand, and easy to maintain.
Although this document is designed for the CSS, you should try to follow the conventions in this document when using the precompilers of various CSS, such as LESS, SASS, or stylus.
2 Code Style
2.1 file
CSS
File Usage NoneBOM
的 UTF-8
Encoding.
Explanation:
Utf-8 encoding has wider adaptability. BOM can cause unnecessary interference when using programs or tools to process documents.
2.2 the indentation
use4
A space as an indentation level is not allowed2
A blank space ortab
Characters.
Example:
.selector {
margin: 0;
padding: 0;
}
Copy the code
2.3 the blank space
The selector
与 {
Must contain Spaces between.
Example:
.selector{}Copy the code
The property name
And after the:
Spaces are not allowed between,:
与 Attribute values
Must contain Spaces between.
Example:
margin: 0;
Copy the code
Column phenotypic attribute values
When written on a single line,.
Must be followed by a space.
Example:
font-family: Arial, sans-serif;
Copy the code
2.4 length
Each line shall not exceed120
A character, unless a single line is indivisible.
Explanation:
A common indivisible scenario is an extremely long URL.
For super long styles, in the style valueThe blank space
Place or.
After a line break, you are advised to group them logically.
Example:
/* Different attribute values are logically grouped */
background:
transparent url(aVeryVeryVeryLongUrlIsPlacedHere)
no-repeat 0 0;
/* Attributes that can be repeated multiple times, one line at a time */
background-image:
url(aVeryVeryVeryLongUrlIsPlacedHere)
url(anotherVeryVeryVeryLongUrlIsPlacedHere);
/* Function-like attribute values can be indented according to the function call */
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.04.rgb(88.94.124)),
color-stop(0.52.rgb(115.123.162)));Copy the code
2.5 the selector
When a rule contains multiple selectors, each selector declaration must have an exclusive row.
Example:
/* good */
.post..page..comment {
line-height: 1.5;
}
/* bad */
.post..page..comment {
line-height: 1.5;
}
Copy the code
>
,+
,~
Leave a space on each side of the selector.
Example:
/* good */
main > nav {
padding: 10px;
}
label + input {
margin-left: 5px;
}
input:checked ~ button {
background-color: #69C;
}
/* bad */
main>nav {
padding: 10px;
}
label+input {
margin-left: 5px;
}
input:checked~button {
background-color: #69C;
}
Copy the code
Values in property selectors must be enclosed in double quotes.
Explanation:
Do not use single quotes. Do not use no quotes.
Example:
/* good */
article[character="juliet"] {
voice-family: "Vivien Leigh", victoria, female;
}
/* bad */
article[character='juliet'] {
voice-family: "Vivien Leigh", victoria, female;
}
Copy the code
2.6 attributes
Property definitions must start on a separate line.
Example:
/* good */
.selector {
margin: 0;
padding: 0;
}
/* bad */
.selector { margin: 0; padding: 0; }
Copy the code
Attribute definitions must end with a semicolon.
Example:
/* good */
.selector {
margin: 0;
}
/* bad */
.selector {
margin: 0
}
Copy the code
Three general
3.1 the selector
Not if it is not necessaryid
,class
Selectors add type selectors to qualify.
Explanation:
In terms of performance and maintainability, it has a certain impact.
Example:
/* good */
#error..danger-message {
font-color: #c00;
}
/* bad */
dialog#error.p.danger-message {
font-color: #c00;
}
Copy the code
The nesting level of the selector should not be greater than3
Level, the position of the rear qualification should be as accurate as possible.
Example:
/* good */
#username input {}
.comment .avatar {}
/* bad */
.page .header .login #username input {}
.comment div * {}
Copy the code
3.2 Attribute Abbreviations
Use attribute abbreviations whenever possible.
Example:
/* good */
.post {
font: 12px/1.5 arial, sans-serif;
}
/* bad */
.post {
font-family: arial, sans-serif;
font-size: 12px;
line-height: 1.5;
}
Copy the code
useborder
/ margin
/ padding
When abbreviating, pay attention to the influence of the implied value on the actual value. Use abbreviations only when you really need to set values in multiple directions.
Explanation:
Abbreviations such as border/margin/padding set multiple attributes at the same time, making it easy to override Settings that do not need to be overridden. If some directions need to inherit other declared values, they should be set separately.
Example:
/* centering <article class="page"> horizontally and highlight featured ones */
article {
margin: 5px;
border: 1px solid # 999;
}
/* good */
.page {
margin-right: auto;
margin-left: auto;
}
.featured {
border-color: #69c;
}
/* bad */
.page {
margin: 5px auto; /* introducing redundancy */
}
.featured {
border: 1px solid #69c; /* introducing redundancy */
}
Copy the code
3.3 Writing sequence of attributes
When written, attributes under the same rule set should be grouped by function and used asFormatting Model > Box Model > Typographic > VisualTo improve the readability of the code.
Explanation:
- Related attributes of Formatting Model include:
position
/top
/right
/bottom
/left
/float
/display
/overflow
等 - Box Model attributes include:
border
/margin
/padding
/width
/height
等
- Typographic properties include:
font
/line-height
/text-align
/word-wrap
等 - Visual attributes include:
background
/color
/transition
/list-style
等
Also, if the Content attribute is included, it should come first.
Example:
.sidebar {
/* formatting model: positioning schemes / offsets / z-indexes / display / ... */
position: absolute;
top: 50px;
left: 0;
overflow-x: hidden;
/* box model: sizes / margins / paddings / borders / ... */
width: 200px;
padding: 5px;
border: 1px solid #ddd;
/* typographic: font / aligns / text styles / ... * /
font-size: 14px;
line-height: 20px;
/* visual: colors / shadows / gradients / ... * /
background: #f5f5f5;
color: # 333;
-webkit-transition: color 1s;
-moz-transition: color 1s;
transition: color 1s;
}
Copy the code
3.4 Clearing floats
When an element needs to be raised to contain internal floating elements, the pseudo-class is setclear
Or triggerBFC
In the manner ofclearfix
. Try not to add empty labels.
Explanation:
The BFC can be triggered in many ways, including:
- Float the none
- The position of the static
- Overflow is not visible
See the article A New Micro ClearFix Hack for A cleaner float method with fewer side effects.
Also note that no clearfix is required for elements that have already triggered the BFC.
3.5 !important
Use as little as possible! important
The statement.
Inline and via labels when you need to enforce styles and do not allow any scenario overrides! important
Define styles.
Explanation:
It is important to note that inline is only used when the design really does not allow any other scene overlay styles! Important style. This scenario is typically used in applications in third-party environments. The z-Index section below is a typical example of one of these special scenarios.
3.6 z – index
willz-index
Hierarchical to manage the visual hierarchy of absolute positioning elements outside the document flow.
Explanation:
Multiple elements of the same level, such as multiple dialogs triggered by user input, use the same Z-index or incrementing Z-index within that level.
It is recommended that each level contain 100 Z-indexes to hold enough elements, and you can adjust this number if there are many elements in each level.
In a controlled environment, the elements that are expected to appear at the top,z-index
Specified as999999
.
Explanation:
Controllable environment is divided into two kinds, one is its own product line environment; Another is that it may be referenced by other product lines, but not by external third party products.
The value 2147483647 is not recommended. In this way, when its product line is referenced by other product lines, the room for upward adjustment will be left in case of hierarchical coverage conflicts.
In a third-party environment, the elements that are expected to appear at the top are inlined with tags! important
That will bez-index
Specified as2147483647
.
Explanation:
Third-party environments are completely out of developers’ control. For elements in a third-party environment, this is required to ensure that the element is not overwritten by other style definitions on its page.
4 values and units
4.1 the text
The text must be enclosed in double quotation marks.
Explanation:
Text type content can be in a selector, property value, and so on.
Example:
/* good */
html[lang|="zh"] q:before {
font-family: "Microsoft YaHei", sans-serif;
content: "" ";
}
html[lang|="zh"] q:after {
font-family: "Microsoft YaHei", sans-serif;
content: "" ";
}
/* bad */
html[lang|=zh] q:before {
font-family: 'Microsoft YaHei', sans-serif;
content: ' ' ';
}
html[lang|=zh] q:after {
font-family: "Microsoft YaHei", sans-serif;
content: "" ";
}
Copy the code
4.2 numerical
When the value is a decimal between 0 and 1, the integer part is omitted0
.
Example:
/* good */
panel {
opacity:.8;
}
/* bad */
panel {
opacity: 0.8;
}
Copy the code
4.3 the url ()
url()
The paths in the function are not quoted.
Example:
body {
background: url(bg.png);
}
Copy the code
url()
The protocol name can be omitted from the absolute path in the function.
Example:
body {
background: url(//baidu.com/img/bg.png) no-repeat 0 0;
}
Copy the code
4.4 the length of the
Length of0
The unit should be omitted when. (Also only units of length can be saved)
Example:
/* good */
body {
padding: 0 5px;
}
/* bad */
body {
padding: 0px 5px;
}
Copy the code
4.5 color
RGB color values must be in hexadecimal notation#rrggbb
. Not allowed to usergb()
.
Explanation:
Color information with alpha can be used with rgba(). When using RGBA (), you must leave a space after each comma.
Example:
/* good */
.success {
box-shadow: 0 0 2px rgba(0.128.0.3);
border-color: # 008000;
}
/* bad */
.success {
box-shadow: 0 0 2px rgba(0.128.0.3);
border-color: rgb(0.128.0);
}
Copy the code
When a color value can be abbreviated, the abbreviation must be used.
Example:
/* good */
.success {
background-color: #aca;
}
/* bad */
.success {
background-color: #aaccaa;
}
Copy the code
Color values do not allow named color values.
Example:
/* good */
.success {
color: #90ee90;
}
/* bad */
.success {
color: lightgreen;
}
Copy the code
The English characters in the color value are lowercase. If you don’t use lower case, you need to keep case consistency within the same item.
Example:
/* good */
.success {
background-color: #aca;
color: #90ee90;
}
/* good */
.success {
background-color: #ACA;
color: #90EE90;
}
/* bad */
.success {
background-color: #ACA;
color: #90ee90;
}
Copy the code
4.6 the 2 d position
Both horizontal and vertical positions must be given.
Explanation:
The 2D position starts at 0% 0%, but when there is only one value in one direction, the value in the other direction is resolved to center. To avoid confusion in understanding, values in both directions should be given. Definition of the background-position property value
Example:
/* good */
body {
background-position: center top; / * * / 50% 0%
}
/* bad */
body {
background-position: top; / * * / 50% 0%
}
Copy the code
5 Text Formatting
5.1 font family
font-family
The font family name in the property should use the English language of the fontFamily Name
, if there are Spaces, they must be placed in quotation marks.
Explanation:
The so-called English Family Name is a metadata of the font file, and the common Name is as follows:
The font | The operating system | Family Name |
---|---|---|
Song style (宋体) | Windows | SimSun |
Black body (medium easy black body) | Windows | SimHei |
Microsoft jas black | Windows | Microsoft YaHei |
Microsoft is black | Windows | Microsoft JhengHei |
Chinese blackbody | Mac/iOS | STHeiti |
Holly blackbody | Mac/iOS | Hiragino Sans GB |
It was dark in the fountain | Linux | WenQuanYi Zen Hei |
Wenquanyi micron black | Linux | WenQuanYi Micro Hei |
Example:
h1 {
font-family: "Microsoft YaHei";
}
Copy the code
font-family
It is written in the order of “Western fonts first, Chinese fonts last”, “good effect (high quality/more satisfying) fonts first, mediocre effect fonts last”, and a universal font family must be specified at the end (serif
/ sans-serif
).
Explanation:
See this article for more details.
Example:
/* Display according to platform */
.article {
font-family: Arial, sans-serif;
}
/* Specific for most platforms */
h1 {
font-family: "Helvetica Neue", Arial, "Hiragino Sans GB"."WenQuanYi Micro Hei"."Microsoft YaHei", sans-serif;
}
Copy the code
font-family
Case insensitive, but in the same project, sameFamily Name
Case must be uniform.
Example:
/* good */
body {
font-family: Arial, sans-serif;
}
h1 {
font-family: Arial, "Microsoft YaHei", sans-serif;
}
/* bad */
body {
font-family: arial, sans-serif;
}
h1 {
font-family: Arial, "Microsoft YaHei", sans-serif;
}
Copy the code
5.2 the shop name
The font size of Chinese content to be displayed on Windows platform should not be smaller than12px
.
Explanation:
Due to The Font rendering mechanism of Windows, text smaller than 12px looks very bad and is hard to read.
5.3 Font Style
Do not use division to display Chinese content on Windows platformnormal
Outside of thefont-style
. Other platforms should also be used with caution.
Explanation:
Since Chinese fonts do not have italic style implementation, all browsers will fallback to Obilique implementation (automatic fitting to italic), and the display effect is poor under small font size (especially under Windows, dot matrix font will be used under small font size), resulting in reading difficulties.
5.4 the word again
font-weight
Properties must be described numerically.
Explanation:
CSS has a total of nine characters from 100 to 900, but is currently limited by the font quality and browser. In fact, it supports 400 and 700 characters, which are equivalent to the keywords Normal and bold respectively.
The browser itself uses a series of heuristic rules to match the font’s Regular weight at <700 and Bold weight at >=700.
But existing browsers are starting to support matching Semibold weights at =600 (see this table), so using numeric descriptions adds flexibility and is shorter.
Example:
/* good */
h1 {
font-weight: 700;
}
/* bad */
h1 {
font-weight: bold;
}
Copy the code
5.5 line height
line-height
When defining text paragraphs, use numeric values.
Explanation:
Set line-height to a numeric value, and the browser will recalculate it based on the font size set for the current element. In a combination of text paragraphs with different sizes, a comfortable spacing between lines can be achieved, avoiding the need to set line-height for each font size.
When line-height is used to control vertical center, it should be set to the same height as the container.
Example:
.container {
line-height: 1.5;
}
Copy the code
6 transformation and animation
usetransition
Should be specifiedtransition-property
.
Example:
/* good */
.box {
transition: color 1s, border-color 1s;
}
/* bad */
.box {
transition: all 1s;
}
Copy the code
Add transitions and animations to properties that the browser can efficiently implement as much as possible.
Explanation:
In this paper, four transformations should be selected where possible:
transform: translate(npx, npx);
transform: scale(n);
transform: rotate(ndeg);
opacity: 0.. 1;
Typically, translate can be used instead of left as the animation property.
Example:
/* good */
.box {
transition: transform 1s;
}
.box:hover {
transform: translate(20px); /* move right for 20px */
}
/* bad */
.box {
left: 0;
transition: left 1s;
}
.box:hover {
left: 20px; /* move right for 20px */
}
Copy the code
7 reactive
Media Query
It must not be arranged separately and must be defined with the associated rules.
Example:
/* Good */
/* header styles */
@media(...). {/* header styles */
}
/* main styles */
@media(...). {/* main styles */
}
/* footer styles */
@media(...). {/* footer styles */
}
/* Bad */
/* header styles */
/* main styles */
/* footer styles */
@media(...). {/* header styles */
/* main styles */
/* footer styles */
}
Copy the code
Media Query
If you have more than one comma separated condition, place each condition on a separate line.
Example:
@media
(-webkit-min-device-pixel-ratio: 2), /* Webkit-based browsers */
(min--moz-device-pixel-ratio: 2), /* Older Firefox browsers (prior to Firefox 16) * /min-resolution: 2dppx), /* The standard way */
(min-resolution: 192dpi) { /* dppx fallback */
/* Retina-specific stuff here */
}
Copy the code
Try to give styles that work best on Retina devices.
8 compatibility
8.1 Attribute Prefix
Attributes with private prefixes are arranged from long to short, aligned by colon position.
Explanation:
Standard attributes are placed at the end, aligned with colons for easy reading and multi-line editing within the editor.
Example:
.box {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
Copy the code
8.2 Hack
You need to addhack
Should consider, as far as possible, whether other means of resolution can be adopted.
Explanation:
If you can achieve the desired style with proper HTML structure or using other CSS definitions, you shouldn’t hack. Hacks often result in increased maintenance costs.
Try to useThe selector hack
Deal with compatibility, notAttribute hack
.
Explanation:
Try to use a SELECTOR hack that conforms to the CSS syntax to avoid the problem that some third-party libraries cannot recognize the hack syntax.
Example:
/* IE 7 */
*:first-child + html #header {
margin-top: 3px;
padding: 5px;
}
/* IE 6 */
* html #header {
margin-top: 5px;
padding: 4px;
}
Copy the code
Try to use simple onesAttribute hack
.
Example:
.box {
_display: inline; /* fix double margin */
float: left;
margin-left: 20px;
}
.container {
overflow: hidden;
*zoom: 1; /* triggering hasLayout */
}
Copy the code