CSS选择器
选择器类型
(1)标签选择器
table {
align:center;
}
(2)类选择器
.box{
width: 50px;
height: 50px;
}
(3)id选择器
#one{
color: green;
font-size:20px:
}
(4)通配符选择器
*{
background-color:gray;
}
(5)复合选择器
<!--后代选择器-->
ol li {
color:red;
}
ol li a {
color:red;
}
<!--子元素选择器:指直接后代,即只能作用于第一个后代-->
ol>li {
color:red;
}
<!--并集选择器:几个样式属性一样时,可以共同调用一个声明-->
div,p {
color:red;
}
<!--链接伪类选择器:一般应用于链接标签,为了确保链接伪类先择期生效,link(未访问),visited(访问过的),hover,active(选定的链接)-->
a:link{
color:#333;
}
<!--focus伪类选择器-->
input:focus {
background-color:yellow;
}
(6)同胞(相邻)选择器(h1 + p)h1和p是兄弟关系而且相邻,也可以写成(h1~p)
+和~区别:+必须是“大哥+二哥”,必须相邻!~可以是“大哥~三妹”或者“二哥~四妹”,可以不相邻
(7)CSS3新增属性选择器
- 利用属性选择器就可以不用借助于类或者id选择器
input[value]必须是input 但是同时具有 value这个属性 选择这个元素 [] - 属性选择器还可以选择属性=值的某些元素
input[type=text]只选择 type =text 文本框的input 选取出来 - 属性选择器可以选择属性值开头的某些元素
div[class^=icon]选择首先是div 然后 具有class属性 并且属性值 必须是 icon开头的这些元素
(8)CSS3新增伪类结构选择器
/* 1. 选择ul里面的第一个孩子 小li */
ul li:first-child {
background-color: pink;
}
/* 2. 选择ul里面的最后一个孩子 小li */
ul li:last-child {
background-color: pink;
}
/*nth-child */
/*3. 选择ul里面的第2个孩子 小li */
ul li:nth-child(2) {
background-color: skyblue;
}
ul li:nth-child(6) {
background-color: skyblue;
}
/* 1.把所有的偶数 even的孩子选出来 */
ul li:nth-child(even) {
background-color: #ccc;
}
/* 2.把所有的奇数 odd的孩子选出来 */
ul li:nth-child(odd) {
background-color: gray;
}
/*3.nth-child(n) 从0开始 每次加1 往后面计算 这里面必须是n 不能是其他的字母 选择了所有的孩子*/
ol li:nth-child(n) {
background-color: pink;
}
/*4.nth-child(2n)母选择了所有的偶数孩子 等价于 even*/
ol li:nth-child(2n) {
background-color: pink;
}
ol li:nth-child(2n+1) {
background-color: skyblue;
}
/* nth-of-type */
/* nth-child 会把所有的盒子都排列序号 */
/* 执行的时候首先看 :nth-child(1) 之后回去看 前面 div */
section div:nth-child(1) {
background-color: red;
}
/* nth-of-type 会把指定元素的盒子排列序号 */
/* 执行的时候首先看 div指定的元素 之后回去看 :nth-of-type(1) 第几个孩子 */
section div:nth-of-type(1) {
background-color: blue;
}
(9)CSS3新增伪元素选择器
利用css创建新标签元素,在父元素内容的前面添加元素/在父元素内容的前面插入元素
div::before {
/* 这个content是必须要写的 */
content: '我';
}
div::after {
content: '小猪佩奇';
}
(10)CSS3新增的伪类选择器
:enabled :disabled 控制表单控件的禁用状态
:checked 单选框或复选框被选中
选择器权重
!important(权值:无穷大)>行内样式style=“”(权值:1000)>id选择器(权值:100)>类选择器、伪类选择器、属性选择器(权值:10)>元素选择器(权值1)>通配符、子选择器、相邻选择器等,如*、>、+,(权值:0)
table {
align:center!important;
}
(1)复合选择器会有权重叠加;例如:li权重是1,ul li 的权重是1+1,故ul li 的权重大于li
(2)继承的样式没有权值。
可继承样式:主要是颜色、文字、字体行间距、行高、对齐方式、列表样式
不可继承样式:border、padding、margin、width、height,很多
优先级
优先级就近原则,同权重情况下定义最近者为准;载入样式以最后载入的样式为准(即后声明的优先)。