Home Web Front-end CSS Tutorial 13 Tips for Writing Good CSS Code

13 Tips for Writing Good CSS Code

Apr 05, 2017 pm 05:11 PM

CSS is not difficult to learn, but in large projects, it becomes difficult to manage. Especially when different people have slightly different writing styles in CSS, it becomes even more difficult to communicate in the team. To this end, I have summarized some ways to achieve efficient and clean methods. CSS code principles:

1. Use Reset but not global Reset

The default attributes of different browser elements are different. Use Reset to reset some default attributes of browser elements to achieve browser compatibility. But it should be noted that please do not use global Reset:

*{ margin:0; padding:0; }
Copy after login

Not only is this slow and inefficient, but it also causes unnecessary elements to have their margins and padding reset as well. It is recommended to refer to the practices of YUI Reset and Eric Meyer. I share the same view as Eric Meyer. Reset is not static. Appropriate modifications need to be made according to the different needs of the project to achieve browser compatibility and operational convenience. The Reset I use is as follows:

/** 清除内外边距 **/
body, h1, h2, h3, h4, h5, h6, hr, p, 
blockquote, /* structural elements 结构元素 */
dl, dt, dd, ul, ol, li, /* list elements 列表元素 */
pre, /* text formatting elements 文本格式元素 */
form, fieldset, legend, button, input, textarea, /* form elements 表单元素 */
th, td, /* table elements 表格元素 */
img/* img elements 图片元素 */{ 
  border:medium none; 
  margin: 0; 
  padding: 0; 
} 
/** 设置默认字体 **/
body,button, input, select, textarea { 
  font: 12px/1.5 '宋体',tahoma, Srial, helvetica, sans-serif; 
} 
h1, h2, h3, h4, h5, h6 { font-size: 100%; } 
em{font-style:normal;} 
/** 重置列表元素 **/
ul, ol { list-style: none; } 
/** 重置超链接元素 **/
a { text-decoration: none; color:#333;} 
a:hover { text-decoration: underline; color:#F40; } 
/** 重置图片元素 **/
img{ border:0px;} 
/** 重置表格元素 **/
table { border-collapse: collapse; border-spacing: 0; }
Copy after login

2. Good naming habits

There is no doubt that messy or unsemantically named code will drive anyone crazy. Code like this:

.aaabb{margin:2px;color:red;}
Copy after login

I think even a beginner would not name a class like this in an actual project, but have you ever thought that such code is also very problematic:

<h1>My name is <span class="red blod">Wiky</span></h1>
Copy after login

The problem is that if you need to change all the original red fonts to blue, then the style will become:

.red{color:bule;}
Copy after login

Such naming will be very confusing, and it will also be very troublesome if the sidebar named .leftBar needs to be modified to the right sidebar. Therefore, please do not use the characteristics of the element (color, position, size, etc.) to name a class or id. You can choose meaningful naming such as: #navigation{...}, .sidebar{...}, .postwrap{ ...}

In this way, no matter how you modify the styles that define these classes or ids, the connection between them and HTML elements will not be affected.

There is another situation. Some fixed styles will not be modified after they are defined. Then you don’t have to worry about the situation just mentioned when naming, such as

.alignleft{float:left;margin-right:20px;} 
.alignright{float:right;text-align:right;margin-left:20px;} 
.clear{clear:both;text-indent:-9999px;}
Copy after login

So for such a paragraph

<p class="alignleft">我是一个段落!</p>
Copy after login

If you need to change this paragraph from the original left alignment to right alignment, then you only need to modify its className to alignright.

3. Code abbreviation

CSS code abbreviations can improve the speed of writing code and simplify the amount of code. There are many properties that can be abbreviated in CSS, including margin, padding, border, font, background and color values, etc. If you learn the code abbreviation, the original code will look like this:

li{ 
    font-family:Arial, Helvetica, sans-serif; 
    font-size: 1.2em; 
    line-height: 1.4em; 
    padding-top:5px; 
    padding-bottom:10px; 
    padding-left:5px; 
}
Copy after login

It can be abbreviated as:

li{ 
    font: 1.2em/1.4em Arial, Helvetica, sans-serif; 
    padding:5px 0 10px 5px; 
}
Copy after login

If you want to know more about how to abbreviate these attributes, you can refer to "Common CSS Abbreviation Syntax Summary" or download CSS-Shorthand-Cheat-Sheet.pdf.

4. Use CSS inheritance

If multiple child elements of a parent element on the page use the same style, it is best to define their same styles on their parent elements and let them inherit these CSS styles. This way you can maintain your code well and reduce the amount of code. So the original code is like this:

#container li{ font-family:Georgia, serif; } 
#container p{ font-family:Georgia, serif; } 
#container h1{font-family:Georgia, serif; }
Copy after login

It can be abbreviated as:

#container{ font-family:Georgia, serif; }
Copy after login

5. Use multiple selectors

You can combine multiple CSS selectors into one if they have a common style. Doing so not only keeps the code concise but also saves you time and space. Such as:

h1{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; } 
h2{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; } 
h3{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }
Copy after login

Can be merged into

h1, h2, h3{ font-family:Arial, Helvetica, sans-serif; font-weight:normal; }
Copy after login

6. Appropriate code comments

Code comments can make it easier for others to understand your code, and reasonable organization of code comments can make the structure clearer. You can choose to add a directory at the beginning of the style sheet:

/*------------------------------------ 
    1. Reset 
    2. Header 
    3. Content 
    4. SideBar 
    5. Footer 
  ----------------------------------- */
Copy after login

In this way, the structure of your code is clear at a glance, and you can easily find and modify the code.

The main content of the code should also be divided appropriately, and the code should even be commented where necessary, which is also conducive to team development:

/***    Header  ***/ 
#header{ height:145px; position:relative; } 
#header h1{ width:324px; margin:45px 0 0 20px; float:left;  height:72px;} 
  
/***    Content ***/
#content{ background:#fff; width:650px; float:left; min-height:600px; overflow:hidden;} 
#content h1{color:#F00}/* 设置字体颜色 */
#content .posts{ overflow:hidden; } 
#content .recent{ margin-bottom:20px; border-bottom:1px solid #f3f3f3; position:relative; overflow:hidden; } 
  
/***    Footer  ***/
#footer{ clear:both; padding:50px 5px 0; overflow:hidden;} 
#footer h4{ color:#b99d7f; font-family:Arial, Helvetica, sans-serif; font-size:1.1em; }
Copy after login

7. Order your CSS code

If the attributes in the code can be sorted alphabetically, it will be faster to find and modify:

/*** 样式属性按字母排序 ***/
p{ 
    background-color:#3399cc; 
    color:#666; 
    font:1.2em/1.4em Arial, Helvetica, sans-serif; 
    height:300px; 
    margin:10px 5px; 
    padding:5px 0 10px 5px; 
    width:30%; 
    z-index:10; 
}
Copy after login

8. Keep CSS readable

Writing readable CSS will make it easier to find and modify styles. I think it's self-evident which of the following two cases is more readable.

/*** 每个样式属性写一行 ***/
p{ 
    background-color:#3399cc; 
    color:#666; 
    font: 1.2em/1.4em Arial, Helvetica, sans-serif; 
    height:300px; 
    margin:10px 5px; 
    padding:5px 0 10px 5px; 
    width:30%; 
    z-index:10; 
} 
  
/*** 所有的样式属性写在同一行 ***/
p{ background-color:#3399cc; color:#666; font: 1.2em/1.4em Arial, Helvetica, sans-serif;  height:300px; margin:10px 5px; padding:5px 0 10px 5px; width:30%; z-index:10; }
Copy after login

When dealing with some selectors with fewer style attributes, I will write a line:

/*** 选择器属性少的写在同一行 ***/
p{ background-color:#3399cc; color:#666;}
Copy after login

This rule is not hard and fast, but no matter which way you write it, my suggestion is to always keep the code consistent. If there are many attributes, write them in separate lines. If there are less than 3 attributes, you can write one line.

9. Choose a better style attribute value

Some attributes in CSS use different attribute values. Although the effects are similar, there are differences in performance, such as

  区别在于border:0把border设为0px,虽然在页面上看不见,但按border默认值理解,浏览器依然对border-width/border-color进行了渲染,即已经占用了内存值。

  而border:none把border设为“none”即没有,浏览器解析“none”时将不作出渲染动作,即不会消耗内存值。所以建议使用border:none;

  同样的,display:none隐藏对象浏览器不作渲染,不占用内存。而visibility:hidden则会。

  10. 使用代替@import

  首先,@import不属于XHTML标签,也不是Web标准的一部分,它对于较早期的浏览器兼容也不高,并且对于网站的性能有某些负面的影响。具体可以参考《高性能网站设计:不要使用@import》。所以,请避免使用@import

  11. 使用外部样式表

  这个原则始终是一个很好的设计实践。不单可以更易于维护修改,更重要的是使用外部文件可以提高页面速度,因为CSS文件都能在浏览器中产生缓存。内置在HTML文档中的CSS则会在每次请求中随HTML文档重新下载。所以,在实际应用中,没有必要把CSS代码内置在HTML文档中:

<style type="text/css" > 
    #container{ .. } 
    #sidebar{ .. } 
</style>
Copy after login

<li style="font-family:Arial, helvetica, sans-serif; color:#666; " >
Copy after login

  而是使用导入外部样式表:

<link rel="stylesheet" type="text/css" href="css/styles.css" />
Copy after login

  12. 避免使用CSS表达式(Expression)

  CSS表达式是动态设置CSS属性的强大(但危险)方法。Internet Explorer从第5个版本开始支持CSS表达式。下面的例子中,使用CSS表达式可以实现隔一个小时切换一次背景颜色:

background-color: expression( (new Date()).getHours()%2 ? "#B8D4FF" : "#F08A00" );
Copy after login

  如上所示,expression中使用了JavaScript表达式。CSS属性根据JavaScript表达式的计算结果来设置。

  表达式的问题就在于它的计算频率要比我们想象的多。不仅仅是在页面显示和缩放时,就是在页面滚动、乃至移动鼠标时都会要重新计算一次。给CSS表达式增加一个计数器可以跟踪表达式的计算频率。在页面中随便移动鼠标都可以轻松达到10000次以上的计算量。

  如果必须使用CSS表达式,一定要记住它们要计算成千上万次并且可能会对你页面的性能产生影响。所以,在非不得已,请避免使用CSS表达式。

  13. 代码压缩

   当你决定把网站项目部署到网络上,那你就要考虑对CSS进行压缩,出去注释和空格,以使得网页加载得更快。压缩您的代码,可以采用一些工具,如YUI Compressor

  利用它可精简CSS代码,减少文件大小,以获得更高的加载速度。

  14. 总结

  在本文中,我力图更详尽的总结书写更高效的CSS代码的原则,但鉴于本人见识和精力有限,我还是希望这些原则能帮助您更好的书写和管理您的CSS代码,不知您又是如何书写CSS的,是否也有一些想要分享的技巧?给我留言吧谢谢~

The above is the detailed content of 13 Tips for Writing Good CSS Code. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to write Bloom filter algorithm using C# How to write Bloom filter algorithm using C# Sep 21, 2023 am 10:24 AM

How to use C# to write a Bloom filter algorithm. The Bloom Filter (BloomFilter) is a very space-efficient data structure that can be used to determine whether an element belongs to a set. Its basic idea is to map elements into a bit array through multiple independent hash functions and mark the bits of the corresponding bit array as 1. When judging whether an element belongs to the set, you only need to judge whether the bits of the corresponding bit array are all 1. If any bit is 0, it can be judged that the element is not in the set. Bloom filters feature fast queries and

Write a method to calculate power function in C language Write a method to calculate power function in C language Feb 19, 2024 pm 01:00 PM

How to write exponentiation function in C language Exponentiation (exponentiation) is a commonly used operation in mathematics, which means multiplying a number by itself several times. In C language, we can implement this function by writing a power function. The following will introduce in detail how to write a power function in C language and give specific code examples. Determine the input and output of the function The input of the power function usually contains two parameters: base and exponent, and the output is the calculated result. therefore, we

How to write a dynamic programming algorithm using C# How to write a dynamic programming algorithm using C# Sep 20, 2023 pm 04:03 PM

How to use C# to write dynamic programming algorithm Summary: Dynamic programming is a common algorithm for solving optimization problems and is suitable for a variety of scenarios. This article will introduce how to use C# to write dynamic programming algorithms and provide specific code examples. 1. What is a dynamic programming algorithm? Dynamic Programming (DP) is an algorithmic idea used to solve problems with overlapping subproblems and optimal substructure properties. Dynamic programming decomposes the problem into several sub-problems to solve, and records the solution to each sub-problem.

How to write a simple hotel reservation system using C++? How to write a simple hotel reservation system using C++? Nov 03, 2023 am 11:54 AM

The hotel reservation system is an important information management system that can help hotels achieve more efficient management and better services. If you want to learn how to use C++ to write a simple hotel reservation system, then this article will provide you with a basic framework and detailed implementation steps. Functional Requirements of a Hotel Reservation System Before developing a hotel reservation system, we need to determine the functional requirements for its implementation. A basic hotel reservation system needs to implement at least the following functions: (1) Room information management: including room type, room number, room

How to use C++ to write a simple student course selection system? How to use C++ to write a simple student course selection system? Nov 02, 2023 am 10:54 AM

How to use C++ to write a simple student course selection system? With the continuous development of technology, computer programming has become an essential skill. In the process of learning programming, a simple student course selection system can help us better understand and apply programming languages. In this article, we will introduce how to use C++ to write a simple student course selection system. First, we need to clarify the functions and requirements of this course selection system. A basic student course selection system usually includes the following parts: student information management, course information management, selection

How to write a simple minesweeper game in C++? How to write a simple minesweeper game in C++? Nov 02, 2023 am 11:24 AM

How to write a simple minesweeper game in C++? Minesweeper is a classic puzzle game that requires players to reveal all the blocks according to the known layout of the minefield without stepping on the mines. In this article, we will introduce how to write a simple minesweeper game using C++. First, we need to define a two-dimensional array to represent the map of the Minesweeper game. Each element in the array can be a structure used to store the status of the block, such as whether it is revealed, whether there are mines, etc. In addition, we also need to define

How to write KNN algorithm in Python? How to write KNN algorithm in Python? Sep 19, 2023 pm 01:18 PM

How to write KNN algorithm in Python? KNN (K-NearestNeighbors, K nearest neighbor algorithm) is a simple and commonly used classification algorithm. The idea is to classify test samples into the nearest K neighbors by measuring the distance between different samples. This article will introduce how to write and implement the KNN algorithm using Python and provide specific code examples. First, we need to prepare some data. Suppose we have a two-dimensional data set, and each sample has two features. We divide the data set into

How to write a binary search algorithm using C# How to write a binary search algorithm using C# Sep 19, 2023 pm 12:42 PM

How to use C# to write a binary search algorithm. The binary search algorithm is an efficient search algorithm. It finds the position of a specific element in an ordered array with a time complexity of O(logN). In C#, we can write the binary search algorithm through the following steps. Step 1: Prepare data First, we need to prepare a sorted array as the target data for the search. Suppose we want to find the position of a specific element in an array. int[]data={1,3,5,7,9,11,13

See all articles