CSS 指层叠样式表 (Cascading Style Sheets),在网页中用来定义网页的元素如何进行显示。
CSS 对大小写不敏感。不过存在一个例外:如果涉及到与 HTML 文档一起工作的话,class 和 id 名称对大小写是敏感的。
书写格式
CSS 规则由两个主要的部分构成:选择器,以及一条或多条声明:
selector {declaration1; declaration2; ... declarationN }
声明的写法按照冒号分隔属性名及属性值:
selector {property: value}
如果有多个声明使用分号隔开:
h1 {color:red; font-size:14px;}
如果属性值有多个单词需要使用引号包括:
p {font-family: "sans serif";}
定义位置
CSS在网页中可以在多个地方进行定义:
内联样式
直接在标签之上编写:
<h1 style="color: brown">Hello</h1>
内部样式表
编写在<head>标签内:
<head>
<meta charset="UTF-8">
<title>Hello</title>
<style type="text/css">
h1{color: brown}
</style>
</head>
外部样式表
存储在外部test.css的文件内:
h1{color: brown}
网页引入:
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="test.css"/>
<title>Hello</title>
</head>
使用次序
当同一个 HTML 元素被不止一个样式定义时,会使用哪个样式呢?
一般而言,所有的样式会根据下面的顺序进行设置:
- 内联样式
- 内部样式表
- 外部样式表
- 浏览器缺省设置
分组
我们可以通过分组将多个标签的样式进行统一的定义,如下:
<style type="text/css">
h1,h2,a {color: crimson;}
</style>
继承
子元素从父元素继承属性。
<style type="text/css">
body {color: crimson;}
</style>
因为所有可视元素都会放在body元素下,所以这么做将改变所有元素的颜色。
选择器
派生选择器
通过依据元素在其位置的上下文关系来定义样式,你可以使标记更加简洁。
我们直接来看一个例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<style type="text/css">
strong {color: green;}
li strong {color: crimson;}
</style>
</head>
<body>
<p>这是一个<strong>重要的</strong>例子</p>
<dl>
<li>这是一个<strong>重要的</strong>例子</li>
</dl>
</body>
</html>
派生选择器使用空格进行分隔,可以指定一个嵌套关系进行样式的定义。
id选择器
指定id元素进行样式定义:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<style type="text/css">
#mydiv {color: green;}
#mydiv p {color: crimson;}
</style>
</head>
<body>
<div id="mydiv">
这是<p>一个</p>测试
</div>
</body>
</html>
id选择器可以配合派生选择器使用。
类选择器
指定对应类名称的元素进行样式定义:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<style type="text/css">
.mydiv {color: green;}
.mydiv p {color: crimson;}
</style>
</head>
<body>
<div class="mydiv">
这是<p>一个</p>测试
</div>
</body>
</html>
同样,可以配合派生选择器使用。
大家这里会不会有一个疑问:既然有了id选择器为啥还需要类选择器,这两个选择器看上去基本上是一致的?这是因为,一个文档中的元素id应该是唯一的,同时一个元素也只能定义一个id,而一个元素可以定义多个类,同时多个元素可以使用同一个类名。
属性选择器
可以为拥有指定属性的 HTML 元素设置样式,而不仅限于 class 和 id 属性。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<style type="text/css">
[title] {color: crimson;}
[title=a] {color: green;}
[title~=b] {color: yellow;}
[title|=c] {color: blue;}
</style>
</head>
<body>
<p>这是一个测试</p>
<p title="">这是一个测试</p>
<p title="a">这是一个测试</p>
<p title="c-b">这是一个测试</p>
<p title="b c">这是一个测试</p>
</body>
</html>
属性选择器在为不带有 class 或 id 的表单设置样式时特别有用:
input[type="text"]
{
width:150px;
display:block;
margin-bottom:10px;
background-color:yellow;
font-family: Verdana, Arial;
} input[type="button"]
{
width:120px;
margin-left:35px;
display:block;
font-family: Verdana, Arial;
}