CSS什么是id 和 Class选择器?

2024-01-18 10:51 小编
一、id选择器
 
  id选择器可以为标有特定id的HTML元素指定特定的样式。
 
  HTML元素以id属性来设置id选择器,CSS中id选择器以"#"来定义。
 
  以下的样式规则应用于元素属性id="demo",id="para1":
 
  #demo{width:500px;height:200px;margin:50pxauto;}
 
  #para1{text-align:center;color:red;}
 
  注意:ID属性不要以数字开头,数字开头的ID在Mozilla/Firefox浏览器中不起作用。
 
  示例代码:
 
  
 
  <!DOCTYPEhtml>
 
  <html>
 
  <head>
 
  <metacharset="UTF-8">
 
  <title>id选择器</title>
 
  <style>
 
  #demo{width:500px;height:200px;margin:50pxauto;}
 
  #para1{text-align:center;color:red;}
 
  </style>
 
  </head>
 
  <body>
 
  <divid="demo">
 
  <pid="para1">HelloWorld!</p>
 
  <p>这个段落不受该样式的影响。</p>
 
  </div>
 
  </body>
 
  </html>
 
  效果图:
 
  1.jpg
 
  二、class选择器
 
  class选择器用于描述一组元素的样式,class选择器有别于id选择器,class可以在多个元素中使用。
 
  class选择器在HTML中以class属性表示,在CSS中,类选择器以一个点"."号显示:
 
  在以下的例子中,所有拥有center类的HTML元素均为居中。
 
  .center{text-align:center;}
 
  示例代码:
 
  
 
  <!DOCTYPEhtml>
 
  <html>
 
  <head>
 
  <metacharset="utf-8">
 
  <title>class选择器/title>
 
  <style>
 
  .center
 
  {
 
  text-align:center;
 
  }
 
  </style>
 
  </head>
 
  <body>
 
  <h1class="center">标题居中</h1>
 
  <pclass="center">段落居中。</p>
 
  </body>
 
  </html>
 
  效果图:
 
  1.png
 
  你也可以指定特定的HTML元素使用class。
 
  在以下实例中,所有的p元素使用class="center"让该元素的文本居中:
 
  p.center{text-align:center;}
 
  注意:类名的第一个字符不能使用数字!它无法在Mozilla或Firefox中起作用。
 
  代码实例:
 
  
 
  <!DOCTYPEhtml>
 
  <html>
 
  <head>
 
  <metacharset="utf-8">
 
  <title>css教程</title>
 
  <style>
 
  p.center
 
  {
 
  text-align:center;
 
  }
 
  </style>
 
  </head>
 
  <body>
 
  <h1class="center">这个标题不受影响</h1>
 
  <pclass="center">这个段落居中对齐。</p>
 
  </body>
 
  </html>


Tag: 什么 选择
在线咨询 拨打电话

电话

13363039260

微信二维码

微信二维码