Writing semantic, efficient and valid HTML and CSS can be a time-intensive process that only gets better with experience. While it is important to take the time to produce high-quality code — as it is what separates professionals from hobbyists — it is equally important to produce websites as expeditiously and efficiently as possible.

编写语义化、高效而又符合规范的HTML和CSS代码不仅要花费大量时间还需要丰富的经验。但为了产生优质代码而投入时间是值得的——代码质量可以体现业余爱好者与专业人士之间的区别——这与快速高效地完成网站建设同样重要。

As web designers, we’re always looking for ways to be more productive. Getting more work done in less time while at the same time maintaining (or improving) our products’ quality is a lifelong quest for many of us.

作为web设计师,人们总是不断寻求提高效率的方法。希望花更少的时间完成更多的工作同时又能够保持(甚至提高)产品的质量,这是包括我在内很多设计师终生的追求。

This article discusses a few fundamental techniques for writing high quality and efficient HTML and CSS.

本文讨论编写优质高效的HTML和CSS代码的一些基本技巧。

Use Templates and Frameworks (Even If It’s Homemade)

使用模板和框架(即便在小工程中)

Using templates and frameworks provides you with a solid baseline from which to start from. For example, CSS frameworks such as the 960 Grid System and Blueprint can save you time in having to write code for bulletproof web page layouts. The purpose of a framework is to reduce development time by avoiding having to repeatedly write cross-browser-tested code for each of your projects. However, take note: Using frameworks involves a learning curve and can bulk up your web page sizes with unnecessary style rules and markup.

使用模板和框架为你找到工程的切入点打下了坚实的基础。例如,960 Grid System和Blueprint这样的CSS框架可以为你节省用来完成网页布局代码的时间;使用框架则可以通过避免为每个工程调试兼容浏览器的代码来缩减开发周期。但另一方面:使用框架会增加学习成本并且会产生多余的样式和标记代码,最终导致网页代码冗余。

Even something as simple as using this XHTML 1.0 strict template — a skeleton for your HTML documents — can be a time-saver.

即便是仅仅使用XHTML 1.0 strict template这样简单的HTML文档框架也能节约时间。

Whether you choose to use a premade framework or not, the notion you should take a note of is just how much code you end up writing over and over again. It’s imperative to discover these repetitive tasks so that you can come up with a system (a custom template/framework) to help you speed up your workflow.

无论使用框架与否,你都必须反复斟酌自己最终的代码量。审视这些重复的工作是必须的,这样你才能总结出最适合你的系统(定制的模板/框架)。

XHTML 1.0 strict template

Conform to XHTML 1.0 Strict Doctype

遵循严格的XHTML 1.0文档类型

Writing under the Strict doctype forces you to produce smarter and specifications-conformant code. Strict doctype lowers your desire to use hacks, deprecated elements, proprietary code, and unconventional markup that in the future will give you grief and maintenance costs related to debugging and updating projects.

编写符合严格XHTML 1.0的文档类型会驱使你产生漂亮而又严格符合规则的代码。严格的文档类型降低你使用hacks、过时元素、专有代码和非主流标记这些可能在将来调试和改动项目时给你带来痛苦和维护成本的风险。

Conform to XHTML 1.0 Strict Doctype

Strict doctype also instructs web browsers to render your web pages under strict W3C specifications, which can reduce browser-specific bugs and thus lowering your development time.

严格的文档类型声明让浏览器用严格的W3C规范来渲染你的网页,这样能够避免网页受浏览器bugs的影响,减少你的开发时间。

Use Good and Consistent Naming Conventions

使用有意义的、一致的命名规则

Always use consistent naming conventions for easier organization and so that you can produce work that is meaningful and expressive.

使用一致命名规则便于组织,同时也可以提高你代码中的可读性和可维护性。

For example, if you use hyphens (-) to separate words in your classes and IDs (e.g.sidebar-blurbabout-us), don’t use underscores (_) for others (e.g. footer_nav,header_logo). Also, using standard and meaningful filenames for documents and directories is a good practice to get into.

举个例子,如果你使用连字符(-)来分隔类和ID字符,那么就别在其他地方用下划线(_)来分隔。同样,为文件和目录使用统一而有意义的命名规则也能达到目的。

Here are some popular classes, IDs and file names:

以下是一些常用的类,ID和文件名:

  • Structural IDs: #header#footer#sidebar#content#wrapper#container
  • Main stylesheet: style.cssstyles.cssglobal.css
  • Main JavaScript library: javascript.jsscripts.js
  • JavaScript directory: jsjavascript or scripts
  • Image directory: imagesimg
  • CSS directory: cssstylesheetsstyles

Naming Conventions

Always use meaningful words for your IDs and classes. For example, using left-coland right-col for div ID attribute values isn’t good because they rely on positional factors rather than semantics. Using something that has greater semantic value such as main-content or aside would be better so that you are giving your layout elements improved meaning and greater flexibility towards changes in the future.

使用有意义的单词作为ID名和类名。比如,使用left-co 和 right-col作为div ID属性值就不好,因为他们是基于位置因素而非基于语义。使用具有更强语义性的词比如“main-content”或者“aside”代替会更好,这样可以赋予布局元素特殊的意义以应对未来网站改版的需求,提高代码可维护性。

In HTML5, the issue of proper naming conventions and uniformity for layout elements has been addressed with the introduction of new HTML elements such as <nav>,<footer> and <article>, but the concept of using proper naming conventions applies to all HTML elements with ID/class attributes, not just layout elements.

在HTML5标准中,伴随着<nav>,<footer>和<article>这些新HTML元素的引入,适当的命名约定和布局元素的统一性问题得到了很好的解决,但使用合适的命名规范这个概念适用于所有带ID/class值的所有HTML元素,而不仅仅是布局元素。

Read more about naming conventions in this article called Structural Naming Convention in CSS.

需要了解更多关于命名规范的内容 可以阅读这篇文章:Structural Naming Convention in CSS.

Good naming conventions are just a best practice in general, but as a bonus, it can help you speed up your development process because of organized and intuitive code, which makes finding and editing things quicker.

总的来说,良好的命名规范只是个习惯,但作为回报它将帮助你提高开发进度,因为组织良好、直观的代码能使查找和编辑变得更加容易。

Understand and Take Advantage of CSS Inheritance

了解并利用好继承性

Instead of assigning every single element a fontcolorbackground, etc., try to take advantage of CSS inheritance rules, especially for fonts, padding and margins. This can reduce the amount of code you have to write and maintain.

避免重复地为每个字体、颜色、背景色这样的元素定义属性,尝试利用CSS的继承性规则,特别对于字体,填充和边距。这将大大减少你需要维护和编写代码的数量。

For example, the following is terser:

例如:

html, body {  background: #eee;  font: normal 11pt/14pt Arial, Helvetica, sans-serif;  color: #000;}ul, ol {  font-size: 18pt;}

Compared to:

相比较于:

html, body {  background: #eee;}p {  font: normal 11pt/14pt Arial, Helvetica, sans-serif;  color: #000;}ul, ol {  font: normal 11pt/18pt Arial, Helvetica, sans-serif;  color: #000;}blockquote {  font: normal 11pt/14pt Arial, Helvetica, sans-serif;  color: #000;}

Reset Your Style Rules

重设你的样式规则

One of the biggest time-sinks in web design is debugging browser-specific bugs. In order to ensure that you start off with a solid baseline — and thus avoid differences across web browsers — consider resetting your CSS. Read more about this subject in the article called Resetting Your Styles with CSS Reset.

web设计过程中最耗时的就是解决浏览器兼容性问题。为了确保你从一开始就立足于坚实的基础—并避免网页的跨浏览器差异—请考虑重设你的CSS。你可以到d Resetting Your Styles with CSS Reset查看更多相关内容。

Just like using CSS frameworks and HTML starter templates, there are several CSS reset templates that you can take advantage of. Here is a couple:

正如使用CSS框架和HTML模板,有许多CSS重设模板可以利用。这儿介绍几个:

Here is Eric Meyer’s Reset CSS:

这是Eric Meyer’sCSS重设代码:

/* v1.0 | 20080212 */html, body, div, span, applet, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre,a, abbr, acronym, address, big, cite, code,del, dfn, em, font, img, ins, kbd, q, s, samp,small, strike, strong, sub, sup, tt, var,b, u, i, center,dl, dt, dd, ol, ul, li,fieldset, form, label, legend,table, caption, tbody, tfoot, thead, tr, th, td {    margin: 0;    padding: 0;    border: 0;    outline: 0;    font-size: 100%;    vertical-align: baseline;    background: transparent;}body {    line-height: 1;}ol, ul {    list-style: none;}blockquote, q {    quotes: none;}blockquote:before, blockquote:after,q:before, q:after {    content: '';    content: none;}/* remember to define focus styles! */:focus {    outline: 0;}/* remember to highlight inserts somehow! */ins {    text-decoration: none;}del {    text-decoration: line-through;}/* tables still need 'cellspacing="0"' in the markup */table {    border-collapse: collapse;    border-spacing: 0;}

The best practice for using CSS reset templates is to fill in the property values of “resetted” styles instead of re-declaring them again.

使用CSS重设模板的最佳实践是使用“重设过”的样式替代属性值而非重新声明这些样式。

For example, in Eric Meyer’s Reset CSS shown above, the line-height of web pages on the site is set to 1. If you know that your line-height needs to be 1.5, then you should change 1 to 1.5.

例如,在Eric Meyer’s 重设CSS中,该网站的 line-height被设置为1,如果你希望其值为1.5,那么你需要修改1为1.5,这时

Do not do this when using CSS reset templates:

别这样使用CSS重设模板

/ * Not good */body {line-height: 1;}...body { line-height: 1.5; }

In addition, it’s best to avoid resetting CSS properties using the universal selector (e.g. * { margin: 0; padding: 0; }) because, performance-wise, it is inefficient and can be resource-taxing on older computers. Read more about using efficient CSS selectors.

另外,最好避免使用通用选择器(比如{margin:0;padding:0;})来重设CSS属性,因为严格来讲,这种低效率的做法有可能会让老旧的计算机吃不消。查看更多相关内容:efficient CSS selectors.

Use CSS Shorthand Properties

使用CSS属性缩写

Writing less CSS means saving time. Not only does using shorthand CSS reduce code-writing, but it also lowers the file sizes of your stylesheets, which ultimately meansfaster page response times. Additionally, shorthand CSS makes your code cleaner and —albeit arguably depending on your preference— easier to read and maintain.

写更少的CSS意味着节约时间。使用CSS缩写不仅能够削减代码编写时间,也可以减小演示表文件的尺寸,最终确保页面加载速度。另外,缩写的CSS代码使你的代码简洁而且更容易阅读和维护—这应该是你想要的效果。

The following are some popular shorthand syntax to memorize and use, with the longhand syntax equivalent preceding it.

以下是常用的便于记忆和使用的缩写语法,与原来的代码具有相同的效果。

Margin and Padding Properties

边距和填充

/* Longhand */margin-top: 0;margin-right: 20px;margin-bottom: 10px;margin-left: 15px;padding-top: 0px;padding-right: 20px;padding-bottom: 0px;padding-left: 20px;
/* Shorthand */margin: 0 20px 10px 15px;padding: 15px 20px 0;

A quick guide:

速记规则:

  • When 4 property values are used – margin/padding: 顶部
  • When 3 property values are used – margin/padding: 顶部
  • When 2 property values are used – margin/padding: 顶部
  • When 1 property value is used – margin/padding: 顶部

Font Properties

字体属性

/* Longhand */font-style: normal;line-height: 11px;font-size: 18px;font-family: Arial, Helvetica, sans-serif;
/* Shorthand */font: normal 18px/11px Arial, Helvetica, sans-serif;

A quick guide:

速记规则:

  • font: [font-stylefont-size/line-heightfont-family];

Background Properties

背景属性

/* Longhand */background-color: #ffffff;background-image: url('../images/background.jpg');background-repeat: repeat-x;background-position: top center;
/* Shorthand */background: #fff url('../images/background.jpg') repeat-x top center;

A quick guide:

速记规则:

  • background: [background-colorbackground-image:url() |background-repeatbackground-position];

To discover more shorthand CSS syntax, take a look at the CSS Shorthand Guide.

查看更多相关内容:CSS Shorthand Guide.

Put Things in the Proper Place and Order

按正确顺序的安排代码位置


Always put things in the conventional place, i.e., where best practices and W3C specifications say they should go. For example, it is best practice to reference external JavaScript libraries after external stylesheet references to improve page responsiveness and to take advantage of the nature of parallel downloading.

确保代码块顺序的和理安排,可以是经过长期实践总结出的 或者是W3C特别说明它们应该在的位置。例如,实践证明JavaScript库文件调用代码置于样式表文件的引入代码之后,可以提高页面载入速度,并有利于发挥并行加载的优势。

This is the best way:

这是正确的方式:

<head>  <!-- CSS on top, JavaScript after -->  <link rel="stylesheet" type="text/css" href="styles.css" />  <script type="text/javascript" src="script.js" /></head>

The suboptimal way:

这是次优的选择:

<head><!-- CSS at the bottom, JavaScript on top -->  <script type="text/javascript" src="script.js" />  <link rel="stylesheet" type="text/css" href="styles.css" /></head>

Note that both code blocks above are valid under specs, but one is better than the other.

虽然以上两种代码块都是有效的,但前者优于后者。

When writing structural markup, think in terms of top to bottom and left to right because that’s the accepted convention. If a sidebar is to the right of a content area and below a header, then the markup should be organized as follows:

当编写结构型的标记时,按从上到下从左到右的顺序,这是不成文的规范。如果边栏在内容区域的右边和页面头部的下边,div结构应该按如下方式组织:

<div id="header"></div><div id="content"></div><div id="sidebar"></div>

However, if the sidebar is on the left, a better practice would be to organize markup like this:

然而,如果边栏是在左边,更好的组织方式应该是这样的:

<div id="header"></div><div id="sidebar"></div><div id="content"></div>

A caveat to the above is when you are optimizing your work for screen readers. The second code block above means that screen readers will always encounter the secondary content (#sidebarbefore the main content (#content), which can hamper the reading of people that require screen-reading assistive technologies. In this case, you could place #sidebar lower down the document and use CSS for visual positioning (i.e. float #sidebar to the left, float #content to the right).

以上两条在你优化屏幕阅读时显得尤为重要,第二种代码块意味着屏幕阅读器会先于主内容块(#content)载入次内容块(#sidebar)。根据屏幕阅读辅助技术的研究,这将会阻碍人们的阅读。在这种情况下,你可以将#sidebar安排到文档靠后的位置并使用CSS定位技术(例如将#sidebar浮动到左边,#content浮动到右边)

In addition to putting HTML elements in their respective places, it’s also important to organize CSS (again, for easier maintenance and readability). In a way, it should mimic the organization of your markup. For example, the #header styles should be before the#footer styles. This is a matter of preference, but it is also a conventional way of organizing style rules.

同时,将HTML元素安排到合适位置对于组织CSS代码(同样是为了提高可读性和可维护性)也是很重要的。在某种程度上,它应该合符你div标记的组织方式。例如,#header的样式应该在#footer样式之前。这是使用偏好的问题,但同时也是组织样式规则的常规方式。

/* Structural Styles */#header {  // header properties}#header .logo {  //site's logo properties}#footer {  // footer properties}

Conclusion

结论

As in most things, the way to better and more efficient coding is to work smarter, not harder. The tips discussed in this article are basic; however, it might also inspire you to delve deeper into these sorts of optimizations and enhancements for improving the craftsmanship of the things you make.

正如其他一切事物,优质和高效的编码方式是为了漂亮的完成工作,而不是使之更加艰难。本文探讨的注意点都是基础的;然而,它也有可能激发你深入这些优化和改进编码的灵感,从而提高你完成作品的技艺。

写于异年同日:

  1. 2012:  感恩节3.95元年费Bluehost主机优惠活动(Bluehost Black Friday Sale)(0)