选择器
所谓选择器,指的是选择施加样式目标的方式。
1.元素选择器
用标签名作为选择器,选中所有相应的元素。
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=utf-8"/>
<title></title>
<styletype="text/css">
div{
font-size:
24px;
color:
magenta;
}
p{
font-size:
36px;
color:
blue;
}
</style>
</head>
<body>
<div>元素选择器</div>
<p>元素选择器</p>
</body>
2. id选择器
顾名思义,是根据id来选择元素,其样式定义形式为:
#idname{
......
}
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=utf-8"/>
<title></title>
<styletype="text/css">
#div1{
width:
100px;
height:
100px;
background-color:orangered;
}
#div2{
width:
100px;
height:
100px;
background-color:sandybrown;
}
</style>
</head>
<body>
<divid="div1"></div>
<divid="div2"></div>
</body>
显示结果为:
3. 类选择器
根据class属性来选择元素,其样式定义形式为:
.className{
......
}
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=utf-8"/>
<title></title>
<styletype="text/css">
.odd{
width:
100px;
height:
100px;
background-color:orangered;
}
.even{
width:
100px;
height:
100px;
background-color:sandybrown;
}
</style>
</head>
<body>
<divclass="odd"></div>
<divclass="even"></div>
<divclass="odd"></div>
</body>
从结果可以看出:.odd{......}定义的样式会施加到所有class=”odd”的元素上,比如上例中的第一个和第三个<div>,当然也包括class=”odd”的<p>。
4.属性选择器
根据某个属性的特性(比如有无、值等)来选择
(1)根据有无某属性来选择
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=utf-8"/>
<title></title>
<styletype="text/css">
[title]{
width:
100px;
height:
50px;
background-color:blue;
border:
1px solid lightcoral;
}
</style>
</head>
<body>
<divtitle="div1">1</div>
<divtitle="div2">2</div>
<div>3</div>
<divtitle="a
div">4</div>
<divtitle="div
a">5</div>
</body>
从结果可以看出,所有具有title属性的元素都应用了蓝色背景色的样式
(2)根据title属性的值来选择
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=utf-8"/>
<title></title>
<styletype="text/css">
[title="div2"]{
width:
100px;
height:
50px;
background-color:blue;
border:
1px solid lightcoral;
}
</style>
</head>
<body>
<divtitle="div1">1</div>
<divtitle="div2">2</div>
<div>3</div>
<divtitle="a
div">4</div>
<divtitle="div
a">5</div>
</body>
从结果可以看出,只有第二个div应用了红色背景的样式,因为只有第二个div的title属性等于div2.
title~=”div”:选中属性值包含指定完整单词的元素,类似word中的全字匹配
title^=”div”:选中title属性值以”div”开头的元素
title$=”div”:选中title属性值以”div”结尾的元素
title*=”div”:选中title属性值包含”div”的元素