博客列表 >css选择器

css选择器

小追
小追原创
2020年06月17日 09:13:10809浏览

CSS选择器


1.简单选择器

①.元素选择器,直接选择如:html body div h1 h2 table p等标签元素;

  1. /*设置p标签字体颜色*/
  2. <style>
  3. p{
  4. color:red;
  5. }
  6. </style>

②.类选择器,选择元素的类属性;

  1. <style>
  2. .class{
  3. width:30px;
  4. }
  5. /*多个类复合应用*/
  6. .class.center{
  7. background-color:red;
  8. }
  9. </style>

③.id选择器,选择元素的id属性,css商业代码中使用较少了,一般只剩下两个作用:配合表单或锚点使用;

  1. <style>
  2. #id{
  3. color:red;
  4. }
  5. </style>

2.上下文选择器

①.后代选择器,选择父元素下所有的同名元素;

  1. /*会选择.container父元素下包含的所有的div元素*/
  2. <style>
  3. .container div{color:red}
  4. </style>

②.父子选择器,用 > 符号规定只选择父元素的子元素;

  1. <stytle>
  2. .container > div{
  3. color:red;
  4. }
  5. </stytle>

③.同级相邻选择器,选择同级相邻的元素;

  1. <style>
  2. .item.center + .item{
  3. background-color:coral;
  4. }
  5. </style>

④.同级所有选择器,选择定位元素后的所有下文

  1. <style>
  2. .item.center ~ .item{
  3. background-color:yellow;
  4. }
  5. </style>

3.结构伪类选择器

①.不分组

:first-child :选择父类下的第一个子元素;

:last-child :选择父类下最后一个子元素;

:nth-child(n) :选择指定子元素,n为指定某个子元素;

:nth-child(2n或even) :选择为偶数的子元素;

:nth-child(2n-1或odd) :选择为奇数的子元素;

:nth-child(n + 4) :选择第4个和后面剩下的所有子元素;

:nth-last-child(-n + 3) :选择最后3个子元素;

:nth-last-child(2) :选择倒数第二个子元素;

②.分组

:last-of-type :选择最后一个;

:nth-of-type() : 指定分组中的一个元素;

:nth-of-type(-n + 3) :指定分组中的前三个;

:nth-last-of-type(-n + 2) :指定分组中最后两个;

4.伪类与伪元素

①.伪类

:target :必须配合ID,实现锚点操作;

:focus :当获取输入焦点时给与样式;

②.伪元素

::selection :只允许设置选中的文本的字体颜色和背景色;

  1. <style>
  2. input::selection{
  3. color:white;
  4. background:red;
  5. }
  6. </style>

::not() :用于不满足条件的元素;

  1. <style>
  2. .list > :not(:nth-of-type(3)){
  3. color:red;
  4. }
  5. </style>

::berore :在元素前添加内容;

:after :在元素后添加内容;


总结:

通过css选择器,可以快速的给目标元素添加样式,非常方便。

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议