W3C errors for duplicate id's

馋奶兔 提交于 2019-12-11 01:04:57

问题


I am using http://validator.w3.org to validate my code.

However I have 45 errors, largely related to duplicate id's.

I thought where possible it would be a good pratctice to re use CSS.

Example code:

CSS

#cloudbullet {
background-color: #85c0bf;
height: 22px;
left: 13px;
margin-top: 7px;
position: relative;
top: 63px;
width: 20px;

HTML

<div id="container1-title" class="">
        <h2>Cloud/Hosting</h2>
        </div>

        <div id="cloudbullet" class="">
        </div>
        <div id="cloudbullet" class="">
        </div>
        <div id="cloudbullet" class="">
        </div>
        <div id="cloudbullet" class="">
        </div>
        <div id="cloudbullet" class="">
        </div>
        <div id="cloudbullet" class="">
        </div>

The effect being that I get 6 css boxes in a vertical row.

Please can someone advise if what I have done is correct and if I should ignore the validation or does this need to be done in a different way?

Thanks,


回答1:


For something that appears several times, you want something that classifies them, not identifies them. An id should be unique in the page.

Even though some things work with duplicate identifiers, it's not certain that it works the same in all browsers, and some things certainly won't work. If for example you want to use the identifier to find the elements using JavaScript, you will run into problems.

Use the class attribute instead. CSS:

.cloudbullet {
  background-color: #85c0bf;
  height: 22px;
  left: 13px;
  margin-top: 7px;
  position: relative;
  top: 63px;
  width: 20px;
}

HTML:

<div id="container1-title">
  <h2>Cloud/Hosting</h2>
</div>

<div class="cloudbullet">
</div>
<div class="cloudbullet">
</div>
<div class="cloudbullet">
</div>
<div class="cloudbullet">
</div>
<div class="cloudbullet">
</div>
<div class="cloudbullet">
</div>



回答2:


An id explicitly is unique. Only a single element in the document must have the id. That's why it's called an id, it's a unique identifier.

If you want to apply the same rule to multiple elements, that's what CSS classes are for.




回答3:


Use classes instead? An HTML ID is unique and can only by used once.[1]



来源:https://stackoverflow.com/questions/24993450/w3c-errors-for-duplicate-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!