CSS
层叠样式表(Cascading Style Sheets)用于美化网页、进行网页布局。
CSS 语法
CSS 规则由两个主要的部分构成:选择器
,以及一条或多条声明
。
selector {declaration1; declaration2; ... declarationN }
每条声明由一个属性和一个值组成。属性(property)是希望设置的样式属性(style attribute)。每个属性有一个值。属性和值被冒号分开。
selector {property: value}
示例:
h1 {color:red; font-size:14px;}
如果值为若干单词,则要给值加引号:
p {font-family: "sans serif";}
CSS样式引入
1、外部样式表
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>
2、内部样式表
<head>
<style type="text/css">
hr {color: sienna;}
p {margin-left: 20px;}
body {background-image: url("images/back40.gif");}
</style>
</head>
3、内联样式
<p style="color: sienna; margin-left: 20px">
This is a paragraph
</p>
选择器
继承
子元素继承父元素的样式,但是并不是所有属性都是默认继承的。通过文档中的 inherited:yes 让属性可以被继承。
<h3 style="color: red">
父元素为红色
<p>
子元素也为红色
</p>
</h3>
1、元素选择器
html {color:black;}
h1 {color:blue;}
h2 {color:silver;}
2、选择器的分组
你可以对选择器进行分组,这样,被分组的选择器就可以分享相同的声明。用逗号将需要分组的选择器分开。在下面的例子中,我们对所有的标题元素进行了分组。所有的标题元素都是绿色的。
h1,h2,h3,h4,h5,h6 {
color: green;
}
3、id 选择器
id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式。id 选择器以 “#” 来定义。
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#red {color:red;}
#green {color:green;}
</style>
</head>
<body>
<p id="red">这个段落是红色。</p>
<p id="green">这个段落是绿色。</p>
</body>
4、类选择器
类选择器以一个点号显示。
.center {text-align: center}
<h1 class="center">
This heading will be center-aligned
</h1>
5、属性选择器
对带有指定属性的 HTML 元素设置样式。可以为拥有指定属性的 HTML 元素设置样式,而不仅限于 class 和 id 属性。
<html>
<head>
<style type="text/css">
[title]
{
color:red;
}
</style>
</head>
<body>
<h1>可以应用样式:</h1>
<h2 title="Hello world">Hello world</h2>
<a title="W3School" href="http://w3school.com.cn">W3School</a>
<hr />
<h1>无法应用样式:</h1>
<h2>Hello world</h2>
<a href="http://w3school.com.cn">W3School</a>
</body>
</html>
6、派生选择器
通过依据元素在其位置的上下文关系来定义样式。
比方说,你希望列表中的 strong 元素变为斜体字,而不是通常的粗体字,可以这样定义一个派生选择器(后代选择器示例):
li strong {
font-style: italic;
font-weight: normal;
}
请注意标记为 <strong> 的蓝色代码的上下文关系:
<p><strong>我是粗体字,不是斜体字,因为我不在列表当中,所以这个规则对我不起作用</strong></p>
<ol>
<li><strong>我是斜体字。这是因为 strong 元素位于 li 元素内。</strong></li>
<li>我是正常的字体。</li>
</ol>
派生选择器包含: CSS 后代选择器、CSS 子元素选择器、CSS 相邻兄弟选择器。
后代选择器:比子选择器的范围大,包含子选择器,且包含子选择器的“子孙”选择器,后代选择器使用"空格
"符号间隔选择器。
<head>
<style type="text/css">
h1 em {color:red;}
</style>
</head>
<body>
<h1>This is a <em>important(斜字体)</em> heading</h1>
<p>This is a <em>important(斜字体)</em> paragraph.</p>
</body>
子选择器:子选择器只是父选择器的一级子元素,使用">
"符号链接选择器。
<head>
<style type="text/css">
h1 > strong {color:red;}
</style>
</head>
<body>
<h1>This is <strong>very very(红色)</strong> important.</h1>
<h1>This is <em>really <strong>very(不是红色)</strong></em> important.</h1>
</body>
相邻兄弟选择器:是拥有相同父元素,且两个元素相邻,使用"+
"符号链接。
<head>
<style type="text/css">
h1 + p {color:red;}
</style>
</head>
<body>
<h1>This is a heading(红色).</h1>
<p>This is paragraph(红色).</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
</body>
h1+p只会对第一个p作用