将样式与HTML文档相关联有四种方法.最常用的方法是内联CSS和外部CSS.
您可以使用< style>将CSS规则放入HTML文档中.元件.此标记位于< head> ...</head>内标签.使用此语法定义的规则将应用于文档中可用的所有元素.以下是通用语法 :
<!DOCTYPE html> <html> <head> <style type = "text/css" media = "all"> body { background-color: linen; } h1 { color: maroon; margin-left: 40px; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body> </html>
与<style>元素关联的属性是:
Attribute | Value | Description |
---|---|---|
type | text/css | Specifies the style sheet language as a content-type (MIME type). This is required attribute. |
media | screen tty tv projection handheld braille aural all | Specifies the device the document will be displayed on. Default value is all. This is an optional attribute. |
您可以使用任何HTML元素的style属性来定义样式规则。 这些规则仅适用于该元素。 这是通用语法:
<element style = "...style rules....">
Attribute | Value | Description |
---|---|---|
style | style rules | The value of style attribute is a combination of style declarations separated by semicolon (;). |
以下是基于上述语法的内联CSS示例:
<html> <head> </head> <body> <h1 style = "color:#36C;"> This is inline CSS </h1> </body> </html>
它将产生以下结果 :
<link>元素可用于在HTML文档中包含外部样式表文件。
外部样式表是一个扩展名为.css的单独文本文件。 您可以在此文本文件中定义所有样式规则,然后可以使用<link>元素将此文件包含在任何HTML文档中。
这是包含外部CSS文件的通用语法:
<head> <link type = "text/css" href = "..." media = "..." /> </head>
与<style>元素关联的属性是:
Attribute | Value | Description |
---|---|---|
type | text css | Specifies the style sheet language as a content-type (MIME type). This attribute is required. |
href | URL | Specifies the style sheet file having Style rules. This attribute is a required. |
media | screen tty tv projection handheld braille aural all | Specifies the device the document will be displayed on. Default value is all. This is optional attribute. |
考虑一个名为mystyle.css的简单样式表文件,其中包含以下规则:
h1, h2, h3 { color: #36C; font-weight: normal; letter-spacing: .4em; margin-bottom: 1em; text-transform: lowercase; }
现在,您可以在任何HTML文档中包含此文件mystyle.css,如下所示:
<head> <link type = "text/css" href = "mystyle.css" media = " all" /> </head>
@import用于以类似于<link>元素的方式导入外部样式表。 这是@import规则的通用语法。
<head> <@import "URL"; </head>
这里URL是具有样式规则的样式表文件的URL。 您也可以使用其他语法:
<head> <@import url("URL"); </head>
以下是演示如何将样式表文件导入HTML文档的示例:
<head> @import "mystyle.css"; </head>
我们已经讨论了在HTML文档中包含样式表规则的四种方法。 以下是覆盖任何样式表规则的规则。
任何内联样式表都具有最高优先级。 因此,它将覆盖在任何外部样式表文件中定义的<style> ... </ style>标记或规则中定义的任何规则。
style> ... </ style>标记中定义的任何规则都将覆盖任何外部样式表文件中定义的规则。
外部样式表文件中定义的任何规则都具有最低优先级,并且仅当上述两个规则不适用时,才会应用此文件中定义的规则。
有许多旧浏览器不支持CSS。 因此,我们应该在HTML文档中编写嵌入式CSS时注意。 以下代码段显示了如何使用注释标记隐藏旧浏览器中的CSS:
<style type = "text/css"> <!-- body, td { color: blue; } --> </style>
很多时候,您可能需要在样式表块中添加其他注释。 因此,在样式表中评论任何部分都非常容易。 你可以简单地把你的评论放在/*..这是样式表中的评论..... * /。
可以使用/ * .... * /以与C和C ++编程语言类似的方式注释多行块。
<!DOCTYPE html> <html> <head> <style> p { color: red; /* This is a single-line comment */ text-align: center; } /* This is a multi-line comment */ </style> </head> <body> <p>Hello World!</p> </body> </html>