CSS:Getting Started:Readable CSS
From MDC
目录 |
[编辑] 资料: 具有可读性的 CSS
可以为样式表添加空白和注释以使其更具可读性。 You can also group selectors together, when the same style rules apply to elements selected in different ways.
[编辑] 空白
空白是指空格,跳格和换行。 添加空白让你的样式表具有更佳的可读性。
我们的范例CSS文件目前是把一条规则都写成一行,且几乎没有空白。在复杂的样式表中,这种排版方式会难于阅读,样式表很难维护。
排版方式的选择是个人的偏好,但如果你的样式表属于共享项目的一部分,这些项目对排版方式可能有它自己的约定。
有些人喜欢紧凑的排版,也就是我们先前使用的方法,只在一行变得很长了,才会分行:
.carrot {color: orange; text-decoration: underline; font-style: italic;}
有些人则喜欢每行一个属性值: .carrot
{
color: orange;
text-decoration: underline;
font-style: italic;
}
有些人使用缩进,通常为两个空格,四个空格或一个跳格: .carrot {
color: orange;
text-decoration: underline;
font-style: italic;
}
有些人喜欢Some people like everything to line up vertically (但这种排版方式很难维护): .carrot
{
color : orange;
text-decoration : underline;
font-style : italic;
}
一些人在排版中使用跳格。一些人则只使用空格。 |
[编辑] 注释
CSS中的注释以/*开始,以*/结束。
You can use comments to make actual comments in your stylesheet, and also to comment out parts of it temporarily for testing purposes.
To comment out part of a stylesheet, place that part in a comment so that the browser ignores it. Be careful where you start and end the comment. The rest of the stylesheet must still have correct syntax.
/* style for initial letter C in first paragraph */
.carrot {
color: orange;
text-decoration: underline;
font-style: italic;
}
|
[编辑] 组选择符
When many elements have the same style, you can specify a group of selectors, separating them with commas. The declaration applies to all the selected elements. 当许多个元素使用同样的样式,你可以将每个元素以逗号分隔,指定一个组选择符,元素之间以逗号隔开。 声明的样式应用于所有被选择的元素。
Elsewhere in your stylesheet you can specify the same selectors again individually, to apply individual style rules to them. 在样式表其它地方,你也可以再单独指定同样的选择符,
| 这条规则使 H1, H2 和 H3 元素具有同样的颜色。
It is convenient to specify the color in only one place, in case it has to be changed. /* color for headings */
h1, h2, h3 {color: navy;}
|
[编辑] 实践:添加注释和改善排版
编辑你的CSS文件,确保其中包含如下规则(不分先后次序):
strong {color: red;}
.carrot {color: orange;}
.spinach {color: green;}
#first {font-style: italic;}
p {color: blue;}
按照你的逻辑重新排列上面的样式表,让它更具可读性。并使用你认为最好的方式为上面的样式表添加空白和注释。
保存文件,然后刷新游览器显示,确保你的更改不影响样式表的正常工作:
| Cascading Style Sheets |
| Cascading Style Sheets |
Comment out part of your stylesheet, without changing anything else, to make the very first letter of your document red:
(不止一种方法。) |
[编辑] 接下来的内容?
您在示例样式表已经使用了斜体文本和下划线文本。 在下一个页面中将介绍更多指定文本外观的方法: Text styles