Table of Contents
Web front-end code specifications
Directory
License
Thanks
Front-end Universal Standards
Golden Rules
Project naming
File naming
<html lang="en"></html>
Copy after login
" >
<html lang="en"></html>
Copy after login
<!-- External CSS --><link rel="stylesheet" href="code-guide.css?1.1.11"><!-- In-document CSS --><style>/* ... */</style><!-- JavaScript --><script src="code-guide.js?1.1.11"></script>
Copy after login
" >
<!-- External CSS --><link rel="stylesheet" href="code-guide.css?1.1.11"><!-- In-document CSS --><style>/* ... */</style><!-- JavaScript --><script src="code-guide.js?1.1.11"></script>
Copy after login
JavaScript 生成标签
CSS 规范
语法
声明顺序
Don't use @import
媒体查询位置
前缀属性
单条声明的声明块
属性简写
Less 和 Sass 中的嵌套
代码注释
class 命名
选择器
代码组织
编辑器配置
JS 规范
空行
变量命名
字符常量
null的使用场景
不适合null的使用场景
undefined使用场景
对象字面量
数组声明
单行注释
多行注释格式
何时使用多行注释格式
文档注释
括号对齐
if else 前后留有空格
switch
for
变量声明
函数声明
Home Web Front-end HTML Tutorial Web front-end code specifications

Web front-end code specifications

Jun 27, 2017 am 09:05 AM
web code front end specification

Web front-end code specifications

Last updated: 2017-06-25

Original article link:

This project is used to record specifications and high-level Maintainable front-end code, this is a front-end code writing specification summarized by analyzing many front-end code libraries on Github.

Directory

  1. Front-end universal specification

  2. HTML specification

  3. CSS specification

  4. JS specification

License

public domain, Just take it.

Thanks

@Ruan YiFeng:

@materliu:https://materliu.github.io/code-guide

@hzlzh:

@tguide:

Front-end Universal Standards

Golden Rules

Always follow the same set of coding standards, which can be listed here or summarized by yourself. If you find any errors in this
specification, please correct them.

No matter how many people work on the same project, make sure every line of code looks like it was written by the same person.

Project naming

Project names are all lowercase and separated by dashes. Camel case naming is prohibited. For example: my-project-name

File naming

File naming refers to the previous rule. When it consists of multiple words, use the dash connection method, for example: error-report.html

When there is a plural structure, plural naming should be used, for example: scripts, styles, images, data-models

The file name can only contain lowercase English letters a~z and sorting numbers 0~ 9 or separator -, it is prohibited to include special symbols, such as spaces, $, etc.

To better express semantics, the file name uses English nouns, or English abbreviations.

It is not allowed to name English words with advertisements, such as ad, adv, adver, advertising, to prevent this module from being filtered out by the browser as a spam advertisement. This is true for any file naming.

  • index.shtml Guide page&Homepage

  • main.shtml Homepage

  • download.shtml Download page

  • act.html Activity list page

  • video.html Video

  • cdkey. html CDKEY page

  • base.css basic style

  • layout.css frame layout

  • ##module .css module style

  • global.css global style

  • font.css font style

  • index.css Home page style

  • link.css Link style

  • print.css Print style

HTML Specification

Syntax

Use four spaces for indentation. This is the only way to ensure that the code displays consistently in various environments.

Nested nodes should be indented (four spaces).

On attributes, use double quotes, not single quotes.

Don't use slashes at the end of auto-closing tags - the HTML5 specification states that they are optional.

Don't ignore optional closing tags (for example, and ).

![](images/logo.png)
Copy after login

HTML5 doctype

Use this simple doctype at the beginning of every HTML page to enable standards mode so that it displays as consistently as possible in every browser.

Although doctype is not case-sensitive, by convention, doctype is capitalized

<!DOCTYPE html>
Copy after login

Language attributes

<html lang="en"></html>
Copy after login

Character encoding

By explicitly declaring the character encoding, you can Ensure that the browser can quickly and easily determine how the page content should be rendered. The

advantage of doing this is that you can avoid using character entity tags in HTML, so that they are all consistent with the
document encoding (generally using UTF-8 encoding).

<meta charset="UTF-8">
Copy after login

IE Compatibility Mode

IE supports specific tags to determine the IE version that should be used to draw the current page. Unless there are strong special needs, it is best to set it to edge mode to notify IE to adopt the latest mode it supports.

<meta http-equiv="X-UA-Compatible" content="IE=Edge">
Copy after login

Responsive
<meta name="viewport" content="width=device-width, initial-scale=1">
Copy after login

Introducing CSS and JavaScript

According to the HTML5 specification, there is usually no need to specify type when introducing CSS and JavaScript, because text/css and text/javascript are their default values ​​respectively. Practicality is better than perfection

Try to follow HTML standards and semantics, but it should not be at the expense of wasting practicality. At all times, problems must be solved with as little complexity and as few labels as possible.

Reduce the number of tags

When writing HTML code, you need to try to avoid redundant parent nodes. Many times, it takes iteration and refactoring to make the HTML less. Consider the following example:

<!-- Not so great --><span class="avatar">
    ![](...)</span><!-- Better -->
![](...)
Copy after login

Attribute order

HTML attributes should appear in a specific order to ensure readability.

class
  1. id
  2. ##name

  3. data-*

  4. src, for, type, href, value, max-length, max, min, pattern

  5. placeholder, title , alt

  6. aria-*, role

  7. required, readonly, disabled

  8. ##class yes Designed for highly reusable components, they should theoretically come first. ids are more specific and should be used sparingly (for example, in-page bookmarks), so they come second.

    Boolean attribute
Boolean attribute refers to an attribute that does not need to declare a value. XHTML requires a declared value for each attribute, but HTML5 does not.

一个元素中 Boolean 属性的存在表示取值 true,不存在则表示取值 false。

简而言之,不要为 Boolean 属性添加取值。

<input type="text" disabled>
Copy after login

JavaScript 生成标签

在 JavaScript 文件中生成标签让内容变得更难查找,更难编辑,性能更差。应该尽量避免这种情况的出现。

CSS 规范

语法

使用四个空格的缩进,这是保证代码在各种环境下显示一致的唯一方式。

使用组合选择器时,保持每个独立的选择器占用一行。

为了代码的易读性,在每个声明的左括号前增加一个空格。

声明块的右括号应该另起一行。

每条声明 : 后应该插入一个空格。

每条声明应该只占用一行来保证错误报告更加准确。

所有声明应该以分号结尾。虽然最后一条声明后的分号是可选的,但是如果没有他,你的代码会更容易出错。

逗号分隔的取值,都应该在逗号之后增加一个空格。

不要在颜色值 rgb() rgba() hsl() hsla()和 rect() 中增加空格,并且不要带有取值前面不必要的 0 (比如,使用 .5 替代 0.5)。

所有的十六进制值都应该使用小写字母,例如 #fff。因为小写字母有更多样的外形,在浏览文档时,他们能够更轻松的被区分开来。

尽可能使用短的十六进制数值,例如使用 #fff 替代 #ffffff。

为选择器中的属性取值添加引号,例如 input[type="text"]。 他们只在某些情况下可有可无,所以都使用引号可以增加一致性。

不要为 0 指明单位,比如使用 margin: 0; 而不是 margin: 0px;。

/* Bad CSS */.selector, .selector-secondary, .selector[type=text] {margin: 0px 0px 15px;background-color: rgba(0, 0, 0, 0.5);box-shadow: 0 1px 2px #CCC, inset 0 1px 0 #FFFFFF
}/* Good CSS */.selector,.selector-secondary,.selector[type="text"] {margin-bottom: 15px;background-color: rgba(0,0,0,.5);box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
}
Copy after login

声明顺序

相关的属性声明应该以下面的顺序分组处理:

  1. Positioning

  2. Box model 盒模型

  3. Typographic 排版

  4. Visual 外观

Positioning 处在第一位,因为他可以使一个元素脱离正常文本流,并且覆盖盒模型相关的样式。盒模型紧跟其后,因为他决定了一个组件的大小和位置。

其他属性只在组件内部起作用或者不会对前面两种情况的结果产生影响,所以他们排在后面。

.declaration-order {/* Positioning */position: absolute;top: 0;right: 0;bottom: 0;left: 0;z-index: 100;/* Box-model */display: block;float: right;width: 100px;height: 100px;/* Typography */font: normal 13px "Helvetica Neue", sans-serif;line-height: 1.5;color: #333;text-align: center;/* Visual */background-color: #f5f5f5;border: 1px solid #e5e5e5;border-radius: 3px;/* Misc */opacity: 1;
}
Copy after login

Don't use @import

<link>相比,@import较慢,增加额外的页面请求,并可能导致其他不可预见的问题。

<!-- Use link elements --><link rel="stylesheet" href="core.css?1.1.11"><!-- Avoid @imports --><style>@import url("more.css?1.1.11");</style>
Copy after login

媒体查询位置

尽量将媒体查询的位置靠近他们相关的规则。不要将他们一起放到一个独立的样式文件中,或者丢在文档的最底部。这样做只会让大家以后更容易忘记他们。这里是一个典型的案例。

.element { ... }.element-avatar { ... }.element-selected { ... }

@media (min-width: 480px) {.element { ...}.element-avatar { ... }.element-selected { ... }
}
Copy after login

前缀属性

当使用厂商前缀属性时,通过缩进使取值垂直对齐以便多行编辑。

/* Prefixed properties */.selector {-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.15);box-shadow: 0 1px 2px rgba(0,0,0,.15);
}
Copy after login

单条声明的声明块

在一个声明块中只包含一条声明的情况下,为了易读性和快速编辑可以考虑移除其中的换行。所有包含多条声明的声明块应该分为多行。

这样做的关键因素是错误检测 - 例如,一个 CSS 验证程序显示你在 183 行有一个语法错误,如果是一个单条声明的行,那就是他了。在多个声明的情况下,你必须为哪里出错了费下脑子。

.span1 { width: 60px; }.span2 { width: 140px; }.span3 { width: 220px; }
Copy after login

属性简写

尽量不使用属性简写的方式,属性简写需要你必须显式设置所有取值。常见的属性简写滥用包括:

  • padding

  • margin

  • font

  • background
    -border
    -border-radius

大多数情况下,我们并不需要设置属性简写中包含的所有值。例如,HTML 头部只设置上下的 margin,所以如果需要,只设置这两个值。过度使用属性简写往往会导致更混乱的代码,其中包含不必要的重写和意想不到的副作用。

/* Bad example */.element {margin: 0 0 10px;background: red;background: url("image.jpg");border-radius: 3px 3px 0 0;
}/* Good example */.element {margin-bottom: 10px;background-color: red;background-image: url("image.jpg");border-top-left-radius: 3px;border-top-right-radius: 3px;
}
Copy after login

Less 和 Sass 中的嵌套

避免不必要的嵌套。可以进行嵌套,不意味着你应该这样做。只有在需要给父元素增加样式并且同时存在多个子元素时才需要考虑嵌套。

// Without nesting.table > thead > tr > th { … }.table > thead > tr > td { … }// With nesting.table > thead > tr {
    > th { … }
    > td { … }
}
Copy after login

代码注释

代码是由人来编写和维护的。保证你的代码是描述性的,包含好的注释,并且容易被他人理解。好的代码注释传达上下文和目标。不要简单地重申组件或者 class 名称。

class 命名

保持 class 命名为全小写,可以使用短划线(不要使用下划线和 camelCase 命名)。短划线应该作为相关类的自然间断。(例如,.btn 和 .btn-danger)。

避免过度使用简写。.btn 可以很好地描述 button,但是 .s 不能代表任何元素。

class 的命名应该尽量短,也要尽量明确。

使用有意义的名称;使用结构化或者作用目标相关,而不是抽象的名称。

命名时使用最近的父节点或者父 class 作为前缀。

使用 .js-* 来表示行为(相对于样式),但是不要在 CSS 中包含这些 class。

选择器

使用 class 而不是通用元素标签来优化渲染性能。

避免在经常出现的组件中使用一些属性选择器 (例如,[class^="..."])。浏览器性能会受到这些情况的影响。

减少选择器的长度,每个组合选择器选择器的条目应该尽量控制在 3 个以内。

只在必要的情况下使用后代选择器 (例如,没有使用带前缀 classes 的情况).

代码组织

以组件为单位组织代码。

制定一个一致的注释层级结构。

使用一致的空白来分割代码块,这样做在查看大的文档时更有优势。

当使用多个 CSS 文件时,通过组件而不是页面来区分他们。页面会被重新排列,而组件移动就可以了。

编辑器配置

根据以下的设置来配置你的编辑器,将这些设置应用到项目的 .editorconfig 文件,来避免常见的代码不一致和丑陋的 diffs。

  • 使用四个空格的缩进。

  • 在保存时删除尾部的空白字符。

  • 设置文件编码为 UTF-8。

  • 在文件结尾添加一个空白行。

JS 规范

语法

使用四个空格的缩进,这是保证代码在各种环境下显示一致的唯一方式。

声明之后一律以分号结束, 不可以省略

完全避免 == != 的使用, 用严格比较条件 === !==

eval 非特殊情况, 禁用!!!

with 非特殊情况, 禁用!!!

单行长度,理论上不要超过80列,不过如果编辑器开启"自动换行"的话可以不考虑单行长度

接上一条,如果需要换行,存在操作符的情况,一定在操作符后换行,然后换的行缩进4个空格

这里要注意,如果是多次换行的话就没有必要继续缩进了,比如说下面这种就是最佳格式。

if (typeof qqfind === "undefined" ||
    typeof qqfind.cdnrejected === "undefined" ||
    qqfind.cdnrejected !== true) {url = "http://pub.idqqimg.com/qqfind/js/location4.js?1.1.11";
} else {url = "http://find.qq.com/js/location4.js?1.1.11";
}
Copy after login

空行

方法之间加

单行或多行注释前加

逻辑块之间加空行增加可读性

变量命名

标准变量采用驼峰标识

使用的ID的地方一定全大写

使用的URL的地方一定全大写, 比如说 reportURL

涉及Android的,一律大写第一个字母

涉及iOS的,一律小写第一个,大写后两个字母

常量采用大写字母,下划线连接的方式

构造函数,大写第一个字母

var thisIsMyName;var goodID;var AndroidVersion;var iOSVersion;var MAX_COUNT = 10;function Person(name) {this.name = name
}
Copy after login

字符常量

一般情况下统一使用单引号

null的使用场景

初始化可能以后分配对象值的变量

与一个可能或可能没有对象值的初始化变量进行比较

传入一个预期对象的函数

从预期对象的函数返回

不适合null的使用场景

不要使用null来测试是否提供参数

不要测试值为null的未初始化变量

undefined使用场景

永远不要直接使用undefined进行变量判断

使用字符串 "undefined" 对变量进行判断

// Badvar person;console.log(person === undefined);    //true// Goodconsole.log(typeof person);    // "undefined"
Copy after login

对象字面量

// Badvar team = new Team();
team.title = "AlloyTeam";
team.count = 25;// Goodvar team = {
    title: "AlloyTeam",count: 25
};
Copy after login

数组声明

// Badvar colors = new Array("red", "green", "blue");var numbers = new Array(1, 2, 3, 4);// Goodvar colors = [ "red", "green", "blue" ];var numbers = [ 1, 2, 3, 4 ];
Copy after login

单行注释

双斜线后,必须跟注释内容保留一个空格

与下一行代码缩进保持一致

可位于一个代码行的末尾,双斜线距离分号四个空格

// Goodif (condition) {// if you made it here, then all security checks passed
    allowed();
}var zhangsan = "zhangsan";    // 双斜线距离分号四个空格,双斜线后始终保留一个空格
Copy after login

多行注释格式

最少三行

前边留空一行

/**
 * 注释内容与星标前保留一个空格
 */
Copy after login

何时使用多行注释格式

难于理解的代码段

可能存在错误的代码段

浏览器特殊的HACK代码

业务逻辑强相关的代码

想吐槽的产品逻辑, 合作同事

文档注释

各类标签 @param @method 等 参考

用于:方法、构造函数、对象

/**
 * here boy, look here , here is girl
 * @method lookGril
 * @param {Object} balabalabala
 * @return {Object} balabalabala
 */
Copy after login

括号对齐

标准示例 括号前后有空格,花括号起始不另换行,结尾新起一行

花括号必须要,即使内容只有一行

涉及 if for while do...while try...catch...finally 的地方都必须使用花括号,即使内容只有一行

if else 前后留有空格

if (condition) {doSomething();
} else {doSomethingElse();
}
Copy after login

switch

switch和括号之间有空格,case需要缩进,break之后跟下一个case中间留一个空白行

花括号必须要, 即使内容只有一行。

switch 的 falling through 一定要有注释特别说明,no default 的情况也需要注释特别说明况

switch (condition) {case "first":// codebreak;case "second":// codebreak;default:// code
}
Copy after login

for

普通for循环, 分号后留有一个空格, 判断条件等内的操作符两边不留空格

前置条件如果有多个,逗号后留一个空格

for-in 一定要有 hasOwnProperty 的判断, 否则 JSLint 或者 JSHint 都会有一个 warn

for (i=0, len=values.length; i<len; i++) {
    process(values[i]);
}var prop;for (prop in object) {// 注意这里一定要有 hasOwnProperty 的判断, 否则 JSLint 或者 JSHint 都会有一个 warn !if (object.hasOwnProperty(prop)) {
        console.log("Property name is " + prop);
        console.log("Property value is " + object[prop]);
    }
}
Copy after login

变量声明

所有函数内变量声明放在函数内头部,只使用一个 var(多了JSLint报错), 一个变量一行, 在行末跟注释, 注释啊,注释啊,亲

函数声明

一定先声明再使用, 不要利用 JavaScript engine的变量提升特性, 违反了这个规则 JSLint 和 JSHint都会报 warn

function declaration 和 function expression 的不同,function expression 的()前后必须有空格,而function declaration 在有函数名的时候不需要空格,没有函数名的时候需要空格。

函数调用括号前后不需要空格

立即执行函数的写法, 最外层必须包一层括号

"use strict" 决不允许全局使用, 必须放在函数的第一行, 可以用自执行函数包含大的代码段, 如果 "use strict" 在函数外使用, JSLint 和 JSHint 均会报错

function doSomething(item) {// do something
}var doSomething = function (item) {// do something
}// Good
doSomething(item);// Bad: Looks like a block statement
doSomething (item);// Good
(function() {    "use strict";function doSomething() {// code
    }
})();
Copy after login

The above is the detailed content of Web front-end code specifications. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What to do if the blue screen code 0x0000001 occurs What to do if the blue screen code 0x0000001 occurs Feb 23, 2024 am 08:09 AM

What to do with blue screen code 0x0000001? The blue screen error is a warning mechanism when there is a problem with the computer system or hardware. Code 0x0000001 usually indicates a hardware or driver failure. When users suddenly encounter a blue screen error while using their computer, they may feel panicked and at a loss. Fortunately, most blue screen errors can be troubleshooted and dealt with with a few simple steps. This article will introduce readers to some methods to solve the blue screen error code 0x0000001. First, when encountering a blue screen error, we can try to restart

GE universal remote codes program on any device GE universal remote codes program on any device Mar 02, 2024 pm 01:58 PM

If you need to program any device remotely, this article will help you. We will share the top GE universal remote codes for programming any device. What is a GE remote control? GEUniversalRemote is a remote control that can be used to control multiple devices such as smart TVs, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, streaming media players and more. GEUniversal remote controls come in various models with different features and functions. GEUniversalRemote can control up to four devices. Top Universal Remote Codes to Program on Any Device GE remotes come with a set of codes that allow them to work with different devices. you may

How to use Copilot to generate code How to use Copilot to generate code Mar 23, 2024 am 10:41 AM

As a programmer, I get excited about tools that simplify the coding experience. With the help of artificial intelligence tools, we can generate demo code and make necessary modifications as per the requirement. The newly introduced Copilot tool in Visual Studio Code allows us to create AI-generated code with natural language chat interactions. By explaining functionality, we can better understand the meaning of existing code. How to use Copilot to generate code? To get started, we first need to get the latest PowerPlatformTools extension. To achieve this, you need to go to the extension page, search for &quot;PowerPlatformTool&quot; and click the Install button

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Create and run Linux ".a" files Create and run Linux ".a" files Mar 20, 2024 pm 04:46 PM

Working with files in the Linux operating system requires the use of various commands and techniques that enable developers to efficiently create and execute files, code, programs, scripts, and other things. In the Linux environment, files with the extension &quot;.a&quot; have great importance as static libraries. These libraries play an important role in software development, allowing developers to efficiently manage and share common functionality across multiple programs. For effective software development in a Linux environment, it is crucial to understand how to create and run &quot;.a&quot; files. This article will introduce how to comprehensively install and configure the Linux &quot;.a&quot; file. Let's explore the definition, purpose, structure, and methods of creating and executing the Linux &quot;.a&quot; file. What is L

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

See all articles