CSS Id 和 Class选择器

    xiaoxiao2022-07-02  106

    1.1 Id和Class选择器

    如果你要在HTML元素中设置CSS样式,你需要在元素中设置"id" 和 "class"选择器。

    1.2 Id选择器

    id选择器可以为标有特定id的HTML元素指定特定的样式。

    HTML元素以id属性来设置id选择器,CSS中id选择器以"#"来定义。

    以下的样式规则应用于元素属性id="para1" 

    ID属性不要以数字开头,数字开头的ID在Mozilla/Firefox浏览器中不起作用。

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> #para1{ color: red; text-align: center; } </style> <script type="text/javascript"></script> </head> <body> <p id="para1">Hello World!</p> <p>这个段落不受该样式的影响。</p> </body> </html>

     1.3 Class选择器

    class选择器用于描述一组元素的样式,class选择器有别于id选择器,class可以在多个元素中使用。class选择器在HTML中以class属性表示,在CSS中,类选择器以一个点"."号显示;在以下的例子中,所有拥有center类的HTML元素均为居中。 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> .center{ text-align: center; color: greenyellow; } </style> <script type="text/javascript"></script> </head> <body> <h1 class="center">标题居中</h1> <p class="center">段落居中</p> </body> </html>

     

    你也可以指定特定的HTML元素使用class。

    在以下实例中, 所有的 p 元素使用 class="center" 让该元素的文本居中:

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> p.center{ text-align: center; color: greenyellow; } </style> <script type="text/javascript"></script> </head> <body> <h1 class="center">这个标题不受影响</h1> <p class="center">这个段落居中对齐。</p> </body> </html>

     类名的第一个字符不能使用数字!它无法在 Mozilla 或 Firefox 中起作用。

    参考菜鸟教程:https://www.runoob.com/css/css-id-class.html

    最新回复(0)