CSS常用选择器:标签选择器,类选择器,ID选择器,派生选择器,子选择器,组合选择器

1:标签选择器:如果是一个声明,则不需要带分号,如果是多个声明,则最后一个声明不需要带分号

h1{
    color: red
}
h1{
    color: red; font-size: 14px
}

2、类选择器:在CSS里用一个点开头表示类别选择器定义,所有类的选择器的名字以一点开始,在句点后面必须以字母开始,类名中允许使用字目,数字,连字号”-“和下划线”_”,类名分大小写,类选择器可以单独使用,也可以也可以与其他元素结合使用。

.important {color:red;}

*.important {color:red;}

结合其他元素使用

p.important {color:red;}

选择器现在会匹配class 属性包含 important 的所有 p 元素,但是其他任何类型的元素都不匹配,不论是否有此 class 属性。

 

3、id选择器:id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式。 id 选择器以 "#" 来定义。

 #red {color:red;}  #green {color:green;}

id选择器只能用一次。 id 选择器和派生选择器 

#sidebar p {font-style: italic;text-align: right;margin-top: 0.5em;}

上面的样式只会应用于出现在 id 是 sidebar 的元素内的段落。 即使被标注为 sidebar 的元素只能在文档中出现一次,这个 id 选择器作为派生选择器也可以被使用很多次: 

#sidebar p{
    font-style: italic; text-align: right; margin-top: 0.5em;
}
#sidebar h2{
    font-size: 1em;font-weight: normal; font-style:italic;   margin: 0;line-height: 1.5;text-align: right;
}

给标签内的标签定义样式。 派生继承器 

h1  strong{
    color:red;
}

只有当<strong>出现在<h1>标签里才改变颜色。 没有出现在<h1>标签内的<strong>事件则不会受到影响。

子选择器:子选择器(child selector)仅是指它的直接后代

#links>a{
    color:blue;
}

组合选择器  在对多个元素应用相同的样式,允许组合多个选择器,用逗号将它们分开。

 h1,h2,h3,h4  {  
    color:red;
}