CSS初步
1.CSS引用
<link href="css/styles.cs" type="text/css" rel="stylesheet">
优先级 行内样式>内部样式=外部样式
2.选择器
(1)通用选择器*{},选取所有元素
(2)类型选择器h1,h2,h3{}
(3)类选择器.note{}应用所有类名为note的元素
标签使用多个类用空格隔开
<p class="question big">一些文字</p>
.question{color:red}
.big{font-size:40px}
p.note{}应用于所有p元素中类名是note的元素
(4)ID选择器#introduction{}
复合选择器
1.交集选择器。
.rich{color:yellow;
}
p.rich{color:red;
}//p且是rich类的元素,交集。p是元素,必须放在开头。
p.rich#wc{
color:green;
}//id为wc,类为rich,元素为p
2.并集选择器
.rich,
.dog,
.pig{color:blue;}
并集选择器或rich,或dog,或Pig
(5)子元素选择器 li>a{}应用于所有父元素是Li的a元素。对其他不起作用
注意和后代选择器区分,子代选择器范围更小更严格。只限于儿子
(6)后代选择器p a{}应用于所有位于
<ul>
<li>抽烟</li>
<li>喝酒</li>
<li>烫头</li>
</ul>
ul li{color:red}
(7)相邻兄弟选择器h1+p{} 应用于h1元素后第一个p元素,只往下看,且只看紧邻的第一个元素
(8)普通兄弟选择器h1~p{}如果有两个P元素都是h1的兄弟元素,两个都被选中。
3.CSS规则级联
<!DOCTYPE html>
<html>
<head>
<title>How CSS Rules Cascade</title>
<style type="text/css">
* {
font-family: Arial, Verdana, sans-serif;}
h1 {
font-family: "Courier New", Courier, monospace;}
i {
color: green;}
i {
color: red;}
b {
color: pink;}
p b {
color: blue !important;}
p b {
color: violet;}
p#intro {
font-size: 100%;}
p {
font-size: 75%;}
</style>
</head>
<body>
<h1>Potatoes</h1>
<p id="intro">There are <i>dozens</i> of different <b>potato</b> varieties.</p>
<p>They are usually described as early, second early and maincrop potatoes.</p>
</body>
</html>
(1)就近原则
如果两个选择器相同,后出现的优先级高于先出现的。
(2)具体性原则
如果一个选择器比其他选择器更加具体,那么具体的选择器优于一般的选择器。
ID选择器>类选择器>元素选择器>通配选择器
h1优于* p b优于p
p#inftro优于 p
(3)重要性,添加!important强调规则重要。加在属性值后如color:blue !important
权重
格式(a,b,c)
a:id选择器个数
b:类,伪类,属性选择器的个数
c:元素、伪元素选择器的个数
4.继承
font-family,text,line,color可以继承。background-color,border不会继承。
将属性值设为inherit来强制继承
<!DOCTYPE html>
<html>
<head>
<title>Inheritance</title>
<style type="text/css">
body {
font-family: Arial, Verdana, sans-serif;
color: #665544;
padding: 10px;}
.page {
border: 1px solid #665544;
background-color: #efefef;
padding: inherit;}
</style>
</head>
<body>
<div class="page">
<h1>Potatoes</h1>
<p>There are dozens of different potato varieties.</p>
<p>They are usually described as early, second early and maincrop potatoes.</p>
</div>
</body>
</html>