• CSS-ID和类选择器


    1、ID和类选择器

    相对于上下文选择器而言,利用它们可以不用考虑文档的层次结构。只要你在html标记中为元素添加了id和class属性,就可以在css选择器中使用ID和类名,直接选中文档中特定的区域

    可以给id和class属性设定任何值,但不能以数字或者特殊符号开头。

    1.1 类属性

    类属性就是HTML元素的class属性,body标签中包含的任何HTML元素都可以添加这个属性

     1 <html>
     2 <head>
     3     <meta charset="utf-8" />
     4     <title>HTML5 Template</title>
     5     <style>
     6         p {font-family:helvetica,sans-serif;font-size:1.2em;}
     7         .specialtext {font-style:italic;}
     8         p.specialtext {color:red;}
     9         p.specialtext span {font-weight:bold;}
    10     </style>
    11 </head>
    12 <body>
    13     <h1 class="specialtext">this is a heading with the <span>same class</span>as the second paragraph.</h1>
    14     <p>this tag has no class.</p>
    15     <p class="specialtext">when a tag has a class attribute,you can target it <span>regardless</span> of its position in the hierarchy.</p>
    16 </body>
    17 </html>
    View Code

    可以给元素添加多个类,比如:

    <p class="specialtext featured">when a tag has a class attribute,you can target it <span>regardless</span> of its position in the hierarchy.</p>

    选择同时存在这两个类名的元素,可以这样写:

    .specialtext.feature {font-size:120%;}

    注意,CSS选择符的两个类名之间没有空格,因为我们只想选择同时具有这两个类名的那个元素。如果加了空格,就变成“祖先/后代”关系的上下文选择符了

    1.2 ID选择器

    ID与类的写法相似,而且表示ID选择符的#的用法,也跟表示类选择符的.号类似

     1 <html>
     2 <head>
     3     <meta charset="utf-8" />
     4     <title>HTML5 Template</title>
     5     <style>
     6         p {font-family:helvetica,sans-serif;font-size:1.2em;}
     7         #specialtext {font-style:italic;}
     8         p#specialtext {color:red;}
     9         p#specialtext span {font-weight:bold;}
    10     </style>
    11 </head>
    12 <body>
    13     <h1 id="specialtext">this is a heading with the <span>same class</span>as the second paragraph.</h1>
    14     <p>this tag has no class.</p>
    15     <p id="specialtext">when a tag has a class attribute,you can target it <span>regardless</span> of its position in the hierarchy.</p>
    16 </body>
    17 </html>
    View Code

     1.3 ID和类选择器的区别

    1.3.1 什么时候使用ID

    ID的用途是在页面中唯一的标志一个元素,同一个页面中的每一个ID属性,都必须有独一无二的名字,换个角度讲,每个ID名在页面中都只能用一次。

    采用唯一ID标识的菜单后,可以使用上下文选择符来选择其中包含的各种类型的标签了。利用ID,可以在CSS中方便的定位到这个元素以及子元素

    1.3.2 什么时候使用类

    类的目的是为了标识一组具有相同特征的元素。但是我们在使用过程中,要避免“类泛滥”,也就是说,不要像使用ID一样,每个类都指定一个不同的类名,然后再为每个类编写规则,可以使用继承或者上下文选择器来让不同的标签共享样式,从而降低编写和维护的CSS量

    总结:ID的用途是在页面标记中唯一地标志一个特定的元素。它能为我们编写CSS规则提供必要的上下文,排除无关的标记,而只选择上下文中的标签;相对于ID而言,类是可以应用给任意多个页面中的任意多个HTML元素的公共标识符,以便我们为这些元素应用相同的CSS。而且,使用类也让为不同标签名的元素应用相同的样式成为可能

  • 相关阅读:
    【Mesh R-CNN】论文翻译(原理部分)
    关于栈的学习记录
    css入门笔记
    前端学习之html基础知识归纳
    navigator url无法跳转跳转问题
    新手小白学会vim脚本配置
    Linux下实现两个变量之间传参
    [Apache Doris] Apache Doris 架构及代码目录解读
    [编程总结] 开源系统平台化建设思路
    论文阅读|PointRend: Image Segmentation as Rendering
  • 原文地址:https://www.cnblogs.com/tiantianxiangshang33/p/5048997.html
Copyright © 2020-2023  润新知