Blogger Information
Blog 15
fans 0
comment 0
visits 10319
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
HTML中常用选择器及其用法示例-2019年1月16日
超超的博客
Original
1126 people have browsed it

常用的选择器有以下几种:

1.标签选择器

2.层级选择器

3.ID选择器

4.类选择器

5.属性选择器

6.群组选择器

7.相邻选择器

8.兄弟选择器

9.伪类:子元素选择器

10.伪类:类型选择器

11.伪类:表单控件

下面开始分析上面提到的标签。

1.标签选择器

标签选择器,就是根据html中的标签来设置其属性,具体格式是“标签名 {属性:值;}”

例如:<ul>www.php.cn</ul>相对应的就是ul { list-style:none;}

2.层级选择器

<ul>

<li>www.php.cn</li>

</ul>

如果想要改变li的样式,其中li是ul的child,我们就可以用 ul li { 属性:值;}。

3.ID选择器

<ul>

<li id="web">www.php.cn</li>

</ul>

现在我们给li添加一个id=“web”,那么我们在写css时就可以这样来写,#web{属性:值;}

当然id也可以给多个元素添加样式,但不能这样做。

4.类选择器

<ul>

<li class="web">www.php.cn</li>

</ul>

现在给li一个class=“web”,那么其css就是这样的“.web{属性:值;}”

class类选择器,可以给多个元素添加样式,是我们常用的选择器。

5.属性选择器

<ul>

<li class="web">www.php.cn</li>

</ul>

属性选择器,就是在标签后面加上其class名或者id名,我们可以这样写,li[class="web"]{属性:值;}

6.群组选择器

<ul>

<li class="web">www.php.cn</li>

<li id="web">www.php.cn</li>

</ul>

当我们想要给予ul中的两个li相同的样式时,可以这样写,#web,.web{属性:值;}

7.相邻选择器

<ul>

<li class="web1">www.php.cn</li>

<li class="web2">www.php.cn</li>

<li class="web3">www.php.cn</li>

</ul>

用相邻选择器,可以设置相邻元素的样式。.web1的相邻元素是.web2,我们可以这样写:.web1 + *{属性:值;},这


样设置的就是》web2的css。

8.兄弟选择器

<ul>

<li class="web1">www.php.cn</li>

<li class="web2">www.php.cn</li>

<li class="web3">www.php.cn</li>

</ul>

<ul>

<li class="web1">www.php.cn</li>

<li class="web2">www.php.cn</li>

<li class="web3">www.php.cn</li>

</ul>

通过兄弟选择器,可以选中从开始元素之后的所有相同元素。

例如:ul ~ * { },可以选中Ul中所有的li元素。

9.伪类:子元素选择器

<ul>

<li class="web1">www.php.cn</li>

<li class="web2">www.php.cn</li>

<li class="web3">www.php.cn</li>

</ul>

选择ul列表中的第一个元素,ul :first-child{ }

选择ul列表中的最后一个元素,ul :last-child{ }

选择ul中的第二个元素,ul :nth-child(2){ }

选择ul中的偶数项元素,ul :nth-child(2n){ }

选择ul中的奇数项元素,ul :nth-child(2n-1){ }

选择ul中的倒数第二个元素,ul :nth-last-child(2){ }

10.伪类:类型选择器

<ul>

<li class="web1">www.php.cn</li>

<li class="web2">www.php.cn</li>

<li class="web3">www.php.cn</li>

</ul>

选择第一个li类型元素,ul li:first-of-type{ }

选择最后一个li类型元素,ul li:last-of-type{ }

选择第二个li类型元素,ul li:nth-of-type(2){ }

11.伪类:表单控件

form :enabled{ background-color: black;},使form中的文本框默认背景变为黑色。

form :checked + * { color:red;},将单选按钮中的文本前景色设置为红色。

form :invalid {color:red},当在控件中输入无效文本时,文本颜色变为红色。

form :focus { background-color: lightgreen},设置控件获取焦点时的样式。

button:hover{background-color:red;},当鼠标悬停在button按钮上时,背景会变成红色。


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!