ID vs CLASS in CSS. Please explain in detail with

2019-03-07 01:44发布

I have heard that ID is unique and can only be used once in a page, but its working fine when used over multiple times on a page. Please let me know the purpose of ID and hows its exactly different from classes?

@HTML FILE

  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <LINK href="special.css" rel="stylesheet" type="text/css">
   <title>Untitled Document</title>
   </head>

    <body>
    <div class="layout">
    <div class="left_box">
    <div id="color"></div>
   </div>

   <div class="right_box">
    <div id="color"></div>
    </div>
     </div>
   </body>
   </html>

@CSS FILE

      @charset "utf-8";
     /* CSS Document */
     .layout {
 width:600px;
  height:600px;
  background-color:#666;
  margin:0 auto;
      }

     .left_box {
  width:300px;
  height:600px;
  float:left;
        }

    .right_box {
 width:300px;
 height:600px;
 float:right;
    }

    #color {
background-color:#CCC;
height:600px;
    }

8条回答
劫难
2楼-- · 2019-03-07 02:40

Using the same ID for multiple items causes your HTML to be invalid.

The simple answer is just that. If you're using an ID (a unique identifier) multiple times you're invalidating your HTML.

Just as chewing gum can be used to stick a painting to a wall, the same ID can be used multiple times because HTML doesn't handle errors in a draconian fashion. It still doesn't make it correct or even a good use of the attribute.

Classes are designed so that you can relate multiple elements on a page. This is what it's designed for.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-07 02:42

If you care for XHTML/HTML validation, then you should use unique IDs.

See this:

Class vs. ID

And

Why must the ID attribute be unique on each page?

Hope it helps.

查看更多
登录 后发表回答