1.元素选择器
常见的html标签元素
h1 { color: red; } body { background: red; }
2.分组选择器
例如body和h2标签的字体颜色都是red,使用逗号将其隔开。
body, h1 { color: red; }
3.通配符选择器
* { color: red; }
4.类选择器
在html标签中使用class属性,然后使用样式属性。
<a class="customClassName1'>hello,world</a>
<a class="customClassName2'>hello,world</a>
<a class="nameOne nameTwo">hello,world</a>
样式表:
.customClassName1 { color: red; background: blue; }
a.customClassName2 {
font-weight: bold;
}
.nameOne.nameTwo {
background: silver;
}
//不能匹配到,没有nameThree
.nameOne.nameThree {
font-weight: bold;
}
5.Id 选择器
id选择器前面使用#。id是html元素唯一标识符
<a id="customId">hello, use id selector</a>
css文件
#customId { font-size: 12px; }
6.属性选择器
通过标签属性来设置样式。两种方式:
1.具体属性名称的值,属性值需要全值匹配:标签名[属性名=‘属性值’]
2.属性名称: 标签名[属性名]
<a name="attrName">hello, world</a>
<a name="attrName2">hello, world</a>
css样式:
a[name] { background: red; }
a[name="atriName2"] {
background: red;
}
7.文档结构方面选择器
7.1 后代选择器
html是文档结构模型的,都有父子节点。可以通过节点关系进行选择。
<div> <h1>1</h1> <span>
<b>2</b>
</span> </div>
css编写:
div h1 { color: red; } div span b { color: blue; }
7.2 选择子元素
<div> <h1>this is first h1</h1> <h2>this is second h2</h2> </div>
子元素css
div > h1 { font-weight: bold; }
7.3 选择相邻兄弟元素
<div> <h1 class="target">1</h1> <h2 class="getTarget">2</h2> <div>
css:
.target + .getTarget { color: red; }
8 伪类和伪元素
8.1 a链接伪类
a链接相关的伪类有5个:
a.静态伪类: :link , :visited
b.动态伪类 : :focus, :hover , :active
使用顺序一般为: link - visited - focus- hover - active
8.2 选择第一个子元素
<div> <h1>first </h1> <h2>second</h2> <div>
css:
div:first-child { color: red; }
8.3 伪元素选择器
<p>first line</p>
<p>first letter</p>
css:
//a. 设置首字母样式
p:first-letter { font-size: 20px; }
//b.设置首行
p:first-line {
color: purple;
}