CSS选择器(一)
一.选择器
1.id选择器
html以id属性设置id选择器,css中id选择器用“#”来定义。
<style type="text/css"> #green{ color:green; text-align:center; font-weight:bold; } </style> <body> <p>无样式</p> <p id="green">有样式</p> </body>
显示:

tips:不能以数字开头,在firefox/mozilla浏览器不起作用
2.class选择器(类选择器)
class区别于id选择器,可以在多个元素中使用。用“.”来定义。
<style type="text/css">
.red{
color:red;
text-align:center;
font-weight:bold;
}
</style>
<body>
<p>无样式</p>
<p class="red">有样式</p>
</body>
显示:

tips:不能以数字开头,在firefox/mozilla浏览器不起作用
3.标签选择器(又叫元素选择器)
以html标签作为css选择器。
<style type="text/css">
h1{
color: blue;
}
</style>
<body>
<h1>有样式</h1>
<h2>无样式</h2>
</body>

4.内联样式
<style type="text/css"> </style> <body> <h1 style="color: yellow;">有样式</h1> <h1>无样式</h1> </body>
显示:

①第四种为内联式css样式。
②前三种为嵌入式css样式,将css代码写在<style="text/css"></style>之间。
③外部式css样式,将css写入单独的文件,以“.css”文件为扩展名,引入到html文件内。
优先级:内联式(4)>嵌入式(1>2>3)>外部式
嵌入式>外部式前提:嵌入式在外部式引入之后。
原则:就近原则
其他选择器举例:
5.包含选择器
格式: A B { ······}
A B为html中元素/标签,表明对处于A中的B元素有效。
<style type="text/css">
div p{
color:red;
}
</style>
<body>
<div><p>有样式</p></div>
<p>无样式</p>
</body>

6.子选择器
格式: A > B {······}
类似包含选择器,区别在于包含选择器可以嵌套更深。
<style type="text/css"> div>p{ color:red; } </style> <body> <div> <p>有样式</p> <table> <tr><td><p>有样式</p></td></tr> </table> </div> <p>无样式</p> </body>

7.兄弟选择器
格式: A~B {······}
A标签匹配选择器的A,B标签匹配选择器的B时,B标签匹配样式。
<style type="text/css"> div~p{ color:coral; } </style> <body> <div> <p>无样式</p> <div></div> <p>有样式</p> </div> <p>有样式</p> <p>有样式</p> </body>


浙公网安备 33010602011771号