CSS中的选择器是CSS规则集的一部分,用于选择无涯教程要设置样式的内容。 id和class都是CSS元素选择器,用于根据分配的名称来标识元素。 CSS ID和class选择器是CSS中最常用的选择器。
在使用选择器的过程中,有时id和class之间会发生混淆。它们都没有任何默认样式信息;他们需要 CSS 来选择它们并将其应用于样式。尽管两者均用于选择元素,但它们在许多方面彼此不同。
id和class之间的区别如下表所示。
class | Id |
---|---|
可以将class应用于各种元素,以便在单个页面上可以多次出现。 | 该ID在页面中是唯一的,只能将其应用于一个特定元素。 |
该class已分配给元素,其名称以"."开头。然后是class的名称。 | ID的名称以"#"符号开头,后跟唯一的ID名称。 |
可以将多个class选择器附加到一个元素上。 | 只能在一个元素上附加一个ID选择器。 |
语法: .class { // CSS的声明 } | 语法: #id{ // CSS的声明 } |
现在分别讨论id和class。
id选择器用于选择HTML元素的id属性,以选择特定元素。 id在页面内始终是唯一的,因此选择它来选择一个唯一的元素。
它用井号(#)加上元素的ID编写。id选择器的示例如下。
在此示例中,选择ID为" para"的元素。
<!DOCTYPE html> <html> <head> <style> #para { text-align: center; color: blue; font-size: 25px; background-color: pink; } </style> </head> <body> <h1> Welcome to the Learnfk.com </h1> <p id = "para">This paragraph will be affected.</p> <p>This paragraph will not be affected.</p> </body> </html>
输出
class选择器用于选择具有特定类属性的 HTML 元素。它用句点字符书写.(句号),后跟class名称。
class选择器的示例如下。
在此示例中,选择的class为" example" 的元素。
<!DOCTYPE html> <html> <head> <style> .example { text-align: center; color: blue; font-size: 25px; } </style> </head> <body> <h1 class="example">This heading is blue and center-aligned.</h1> <p class="example">This paragraph is blue and center-aligned.</p> </body> </html>
输出
也可以使用class选择器来设置特定元素的样式,无论它是否应用于其他元素。如果需要指定只影响一个特定的HTML元素,则必须将元素名称与class选择器一起使用。
从以下示例中可以清楚地看出。
<!DOCTYPE html> <html> <head> <style> p.example { text-align: center; color: blue; font-size: 25px; } </style> </head> <body> <h1 class="example">This heading is not effected.</h1> <p class="example">This paragraph is blue and center-aligned.</p> </body> </html>
输出
还有另一个例子,无涯教程在同一个元素上应用多个class。
在此示例中,在段落元素上使用两个class(example 和 para ),并使用这两个class对段落进行样式设置。
<!DOCTYPE html> <html> <head> <style> .example { text-align: center; color: red; font-size: 1cm; } .para{ font-family: Lucida Calligraphy; text-shadow: 5px 8px 9px yellow; } </style> </head> <body> <h1 class="example">This heading is red and center-aligned.</h1> <p class="example para">This paragraph is red and center-aligned with a font-family "Lucida Calligraphy" and text-shadow.</p> </body> </html>
输出
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Spring Boot与Kubernetes云原生微服务实践 -〔杨波〕