CSS的概念
- Cascading Style Sheet 级联样式表
- 表现HTML或XHTML文件样式的计算机语言
CSS基本语法结构
style标签
<style type="text/css">
h1 {
font-size:12px;
color:#F00;
}
</style>
HTML中引入CSS样式
- 行内样式
<h1 style="color:red;">style属性的应用</h1>
<p style="font-size:14px; color:green;">直接在HTML标签中设置的样式</p>
- 内部样式表
<style>
h1{color: green; }
</style>
- 外部样式表
<head>
……
<link href="style.css" rel="stylesheet" type="text/css" />
……
</head>
CSS样式优先级
- 行内样式>内部样式表>外部样式表
- 就近原则
基本选择器
- 标签选择器
- 类选择器
- ID选择器
小结
-
标签选择器直接应用于HTML标签
-
类选择器可在页面中多次使用
-
ID选择器在同一个页面中只能使用一次
优先级:ID选择器>类选择器>标签选择器
层次选择器
后代选择器 body p{color:darkblue;}
子选择器body>p{color:darkblue;}
相邻兄弟选择器 h1+p{color:darkblue;}
通用兄弟选择器 h1~p{color:darkblue;}
结构伪类选择器
ul li:first-child{ background: red;}
ul li:last-child{ background: green;}
p:nth-child(1){ background: yellow;}
p:nth-of-type(2){ background: blue;}
使用E F:nth-child(n)和E F:nth-of-type(n)的关键点
- E F:nth-child(n)在父级里从一个元素开始查找,不分类型
- E F:nth-of-type(n)在父级里先看类型,再看位置
属性选择器
- a[id] { background: yellow; } 含有id属性的a元素变黄色
- a[id=first] { background: red; } 含有id=first属性的a元素变红色,属性和属性值必须完全匹配才能被选中
- a[class*=links] {background: red; } 元素有class属性包含links字符串变红色
- a[href^=http] {background: red; } 含有href的a元素并且以http开头变红色
- a[href$=png] { background:red; } 含有href的a元素并且以png结尾变红色