PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

博客列表 > css元素选择器

css元素选择器

冰雪琉璃
冰雪琉璃 原创
2021年03月24日 09:53:22 600浏览

css选择器有哪些?

1.css选择器
2.id选择器
3.tag(标签选择器)
4.伪类选择器
5.属性选择器
6.子元素选择器
7.包含选择器
8.兄弟选择器
9.相邻选择器
10.群选择器

选择器的优先级

  • !important>行内>id>class>tag>通配符*

    语法

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Document</title>
    6. <style type="text/css">
    7. .lis{
    8. background-color:red;
    9. }
    10. #lis{
    11. background-color:#000;
    12. }
    13. div{
    14. background-color:pink;
    15. }
    16. ul>li{
    17. color:red;
    18. }
    19. ul li{
    20. color:green;
    21. }
    22. </style>
    23. </head>
    24. <body>
    25. <div class="lis">
    26. > "我是class选择器缩写.lis"
    27. </div>
    28. <div id="lis">
    29. > "我是id选择器缩写为#lis"
    30. </div>
    31. <div>
    32. "我是tag标签选择器"
    33. </div>
    34. <ul>
    35. <li>item1</li>
    36. <li>item2</li>
    37. <li>itme3</li>
    38. <li>item4</li>
    39. <li>
    40. <ul>
    41. <li>item_1</li>
    42. <li>item_2</li>
    43. </ul>
    44. </li>
    45. </ul>
    46. </body>
    47. </html>

    类选择器要有一个父元素作为查询起点

    伪类选择器语法

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Document</title>
    6. <style type="text/css">
    7. /*选中ul的所有子元素*/
    8. ul>li{
    9. color:red;
    10. }
    11. /*选中最后一个li*/
    12. ul li:last-child{
    13. background-color: red;
    14. }
    15. /*选中第三个li*/
    16. .list :nth-child(3){
    17. background-color: pink;
    18. }
    19. /*选中第三个li同上*/
    20. .list > li:nth-of-type(3){
    21. background-color: red;
    22. }
    23. /*选中唯一li*/
    24. ul li:only-of-type{
    25. background-color: green;
    26. }
    27. /*.first之后相邻兄弟元素*/
    28. .first+p{
    29. background-color: #000;
    30. }
    31. /*.first所有的兄弟元素*/
    32. .first~p{
    33. background-color: #ccc;
    34. }
    35. </style>
    36. </head>
    37. <body>
    38. <ul class="list">
    39. <li>item1</li>
    40. <li>item2</li>
    41. <li>item3</li>
    42. <li>item4</li>
    43. <li>item5</li>
    44. <li>item6</li>
    45. <li>item7</li>
    46. <p class="first">我是第一个p元素</p>
    47. <p>我是第二个p元素</p>
    48. <p>我是第三个p元素</p>
    49. <li>item8</li>
    50. <li>item9</li>
    51. </ul>
    52. <ul>
    53. <li>我是p元素</li>
    54. </ul>
    55. </body>
    56. </html>

    总结:

  • 选择任何一个元素::nth-of-type(n)
  • 选择第一个::first-of-type
  • 选择最后一个::last-of-type
  • 选择倒数某一个::nth-last-of-type(n)
  • 唯一子元素::only-of-type
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议