简体   繁体   English

id vs CSS中的类声明

[英]id vs class declarations in css

I have the following html structure 我有以下html结构

<div id="content">
   <div id="transport">
      <div id="header">Header Text</div>
       <div id="image"></div>
       <div id="right_content">Lots of text</div>
   </div>
 </div>

Is there a better way to arrange the css for the above rather than use ids for all of the divs? 有没有一种更好的方法来为上面的代码安排CSS,而不是为所有div使用id?

IDs can only be used once in a document. ID在文档中只能使用一次。 Classes can be reused throughout the document. 可以在整个文档中重用类。 Styles attached to IDs trump styles attached to classes. 附加到ID的样式胜过附加到类的样式。

Other than that, it's entirely up to you and the particular content you are marking up. 除此之外,这完全取决于您和您要标记的特定内容。

Looking at your sample code, I would recommend using an actual header tag instead of a div with an ID of header. 查看您的示例代码,我建议您使用实际的标头标记,而不是ID为header的div。

Why not change those to classes and have only the top level container with an ID? 为什么不将其更改为类,而仅将顶级容器具有ID? That way you can target it with the top level ID. 这样,您可以将其定位为顶级ID。

You should also remove the header DIV and use a H2 or H3 tag. 您还应该删除标题DIV,并使用H2或H3标签。

<div id="content">
   <div class="transport">
       <h2>Header</h2>
       <div class="image"></div>
       <div class="right_content">Lots of text</div>
   </div>
 </div>

Your CSS would look like 您的CSS看起来像

#content .transport {}
#content h2 {}
#content .image

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM