CSS 概述
- 层叠样式表(Cascading Style Sheets)
- 定义如何显示HTML文档
- 内容与样式分离,便于管理
- 存储在CSS文件中
- 外部样式表,多个样式可层叠为一
HTML 标签原本被设计为用于定义文档内容。实现浏览器布局。CSS实现样式表现,布局与样式分离,甚至可以在同一个 HTML 文档内部引用多个外部样式表
层叠次序
- 浏览器缺省设置
- 外部样式表
- 内部样式表(位于* head* 标签内部)
- 内联样式(在 HTML 元素内部) —此优先级最高
CSS 语法
css规则:selector {declaration1;declaration2;… declarationN;} 结尾也增加一个分号,减少错误的发生
h1 {color:red ;font-size : 14px;}
selector : 为需要改变的HTML元素 —h1
declaration : 一个属性和一个值组成 — color:red
- 值的不同写法和单位
p {color:red}
p { color: #ff0000; }
p { color: #f00; }
p { color: rgb(255,0,0); }
p { color: rgb(100%,0%,0%); } —使用百分百时,使用0% - 增强样式的可读性
p {
text-align: center;
color: black;
font-family: arial;
} 空格和大小写,与 HTML 文档一起工作的话,class 和 id 名称对大小写是敏感的,与 HTML 文档一起工作的话,class 和 id 名称对大小写是敏感的
选择器分组 —共享相同的声明
h1,h2,h3,h4,h5,h6 {
color: green;
}继承及其问题 —子元素从父元素继承属性
body {
font-family: Verdana, sans-serif;
}
body的子元素可以继承他的属性值,但Netscape4 不支持继承,而且忽略。IE中表格内的样式会被忽略—兼容问题需考虑进去body {
font-family: Verdana, sans-serif;
}p, td, ul, ol, li, dl, dt, dd {
font-family: Verdana, sans-serif;
}浏览器不支持继承,但可以理解 组选择器
如果你希望子元素不继承父元素的属性,可以单独为它创建自己的特殊规则,例如:
p {
font-family: Times, "Times New Roman", serif;
}
选择器
派生选择器 : 派生选择器允许你根据文档的上下文关系来确定某个标签的样式
li strong {
font-style: italic;
font-weight: normal;
}
只有当 li 元素中的 strong 元素 才应用该样式,无需为 strong 元素定义特别的 class 或 id- id 选择器 : id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式。 —“#”定义
#red {color:red;}
#green {color:green;}
<p id="red">这个段落是红色。</p>
<p id="green">这个段落是绿色。</p>
在现代布局中,id 选择器常常用于建立派生选择器
#sidebar p {
font-style: italic;
text-align: right;
先找到id 再找p
类选择器
.center {text-align: center} #定义一个CSS类
类名的第一个字符不能使用数字!它无法在 Mozilla 或 Firefox 中起作用
也可用作派生选择器属性选择器
可以为拥有指定属性的 HTML 元素设置样式,而不仅限于 class 和 id 属性。
[title]
{
color:red;
}设置表单的样式
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;
}