📜  解释 CSS 中不同类型的选择器

📅  最后修改于: 2022-05-13 01:56:48.500000             🧑  作者: Mango

解释 CSS 中不同类型的选择器

CSS 选择器选择 HTML 元素用于样式设置。 CSS 选择器根据其 id、类、类型、属性等选择 HTML 元素。

有许多基本的不同类型的选择器。

  • 元素选择器
  • 标识选择器
  • 类选择器
  • 通用选择器
  • 组选择器

HTML 代码:考虑示例代码以更好地理解选择器及其用途。

HTML


  

    

  

    

        Sample Heading     

       

        Geeks for Geeks is a computer science          portal for geeks and computer enthusiasts.         Geeks for geeks provide a variety of          services for you to learn, thrive and         also, have fun! Free Tutorials, Millions          of Articles, Live, Online and Classroom          Courses, Frequent Coding Competitions,         Webinars by Industry Experts, Internship          opportunities and Job Opportunities.     

       
        Geeks for geeks is a computer science          portal for geeks and computer enthusiast.         Geeks for geeks provide a variety of          services for you to learn, thrive and         also, have fun! Free Tutorials, Millions          of Articles, Live, Online and Classroom          Courses, Frequent Coding Competitions,         Webinars by Industry Experts, Internship          opportunities and Job Opportunities.     
       

        Geeks for geeks is a computer science          portal for geeks and computer enthusiast.         Geeks for geeks provide a variety of          services for you to learn, thrive and         also, have fun! Free Tutorials, Millions          of Articles, Live, Online and Classroom          Courses, Frequent Coding Competitions,         Webinars by Industry Experts, Internship          opportunities and Job Opportunities.     

  


我们将对上述 HTML 代码应用 CSS 规则。

1、元素选择器:元素选择器根据元素名称(或标签)选择HTML元素,例如p、h1、div、span等。

style.css:上述HTML代码中使用了以下代码。您可以看到应用于所有

标签和

标签的 CSS 规则。

h1 {
    color: red;
    font-size: 3rem;
}

p {
    color: white;
    background-color: gray;
}

输出:

2. id 选择器: id选择器使用 HTML 元素的id属性来选择特定元素。

注意:元素的id在页面上是唯一的,以使用id选择器。

style.css:在上面的 HTML 代码中使用了以下代码,使用了 id 选择器。

#div-container{
    color: blue;
    background-color: gray;
}

输出:

下面的 CSS 规则将应用于 id=”div-container” 的 HTML 元素:

3. 类选择器:类选择器选择具有特定类属性的 HTML 元素。

style.css:在上面使用类选择器的 HTML 代码中使用了以下代码。要使用类选择器,您必须在 CSS 中使用 (.) 后跟类名。此规则将应用于类属性为“ paragraph-class ”的 HTML 元素

.paragraph-class {
    color:white;
    font-family: monospace;
    background-color: purple;
}

输出:

4、universal-selector: CSS中的*选择器用于选择HTML文档中的所有元素。它还选择在另一个元素下的所有元素。

style.css:在上面的 HTML 代码中使用了以下代码,使用了通用选择器。此 CSS 规则将应用于页面上的每个 HTML 元素:

* {
  color: white;
  background-color: black;
}

输出:

5. Group-selector:这个选择器用来给所有逗号分隔的元素设置相同的样式。

style.css:下面的代码在上面的 HTML 代码中使用了组选择器。假设您想将通用样式应用于不同的选择器,而不是单独编写规则,您可以将它们分组编写,如下所示。

#div-container, .paragraph-class, h1{
    color: white;
    background-color: purple;
    font-family: monospace;    
}

输出: