CSS选择器

html-css011

CSS选择器,第1张

id:指定标签的唯一标识,定位到页面上唯一的元素。

使用场景: 使用#name定义(name为id名,可任意取名),使用id="name"调用,其优先级高于类选择器,一个标签只能有一个id且每个id只能使用一次,多用于页面分块的块级标签上。

class :类选择器,指定标签的类名,定位到页面上某一类的元素 。

使用场景:使用.name定义(name为类名,可任意取名),使用class="name"调用,一个标签可以有多个类且同一个类可以用到不同的标签上,多用于多个标签样式相似或完全相同时。

* {} /* a=0 b=0 c=0 d=1 ->0,0,0,0 */

p {} /* a=0 b=0 c=0 d=1 ->0,0,0,1 */

a:hover {} /* a=0 b=0 c=1 d=1 ->0,0,1,1 */

ul li {} /* a=0 b=0 c=0 d=2 ->0,0,0,2 */

ul ol+li {} /* a=0 b=0 c=0 d=3 ->0,0,0,3 */

h1+input[type=hidden]{} /* a=0 b=0 c=1 d=2 ->0,0,1,1 */

ul ol li.active {} /* a=0 b=0 c=1 d=3 ->0,0,1,3 */

#ct .box p {} /* a=0 b=1 c=1 d=1 ->0,1,1,1 */

div#header:after {} /* a=0 b=1 c=0 d=2 ->0,1,0,2 */

style="" /* a=1 b=0 c=0 d=0 ->1,0,0,0 */

先比较a,a大的权重最大,再依次比较b,c,d

#header{ }

id选择器,匹配特定id为header的元素

.header{ }

类选择器,匹配class包含header的元素

.header .logo{ }

后代选择器,匹配class为header元素所有的后代(不只是子元素、子元素向下递归)

calss为logo的元素

.header.mobile{ }

匹配class既有header又有logo的元素

.header p, .header h3{ }

同时匹配class为header所有后代元素p和class为header所有后代元素h3

#header .nav>li{ }

匹配id为header元素所有后代中calss为nav的所有直接子元素li

#header a:hover{ }

匹配id为header所有后代中鼠标悬停其上的a元素

#header .logo~p{ }

匹配id为header所有后代中class为logo之后的同级元素p(无论直接相邻与否)

#header input[type="text"]{ }

匹配id为header所有后代中属性type值为text的元素

n的取值

1,2,3,4,5

2n+1, 2n, 4n-1

odd, even

<style>.item1:first-child{ color: red} .item1:first-of-type{ background: blue} </style><div class="ct"><p class="item1">aa</p><h3 class="item1">bb</h3><h3 class="item1">ccc</h3></div>

在CSS中可使用:nth-child()选择器来实现表格隔行变色效果。:nth-child()选择器用于根据元素在一组兄弟中的位置来匹配元素;它匹配第n个子元素。语法:其中arg是表示匹配元素的模式的参数;它可以是一个数字(number)、一个关键字(odd 或 even)或一个函数式。想要隔行设置表格的行颜色需要使用到关键字(odd 或 even),下面就来介绍一下: ●  odd :表示位置为奇数的元素,即1,3,5等。 ●  even: 表示位置为偶数的元素,即2,4,6等。示例1: 为在表中交替的偶数行设置颜色 效果图:示例2: 为在表中交替的奇数行设置颜色 效果图: 更多 web开发 知识,请查阅 HTML中文网 !!

odd代表奇数,even是偶数。

假设您的选择器是li的话,那么写法如下:

li:nth-child(odd) {

color: blue

}

这样您奇数行的li标签文字颜色就是蓝色的了。