哪种方法更好?CSS类或ID?

Which method is better? CSS classes or ID#39;s?(哪种方法更好?CSS类或ID?)
本文介绍了哪种方法更好?CSS类或ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

让我们考虑这两种编写相同代码的方式:

Let's consider these 2 ways of writing the same code:

方法一

<div id="header">
    <div id="user">
        <a id="userName">Username</a>
        <a id="userImage">Userimage</a>
    </div>
</div>

方法二

<div id="header">
    <div class="user">
        <a class="name">Username</a>
        <a class="image">Userimage</a>
    </div>
</div>

方法一的CSS

#userName { color: white; }
#userImage { height: 50px; width: 50px; }

方法2的CSS

#header div.user a.name { color: white; }
#header div.user a.image { height: 50px; width: 50px; }

在我看来,方法 2 更简洁,因为您永远不会得到像 userImageInnerBox 这样的 ID.现在从技术上讲,哪种方法最好,为什么?

It seems to me that Method 2 is cleaner, since you will never end up with IDs like userImageInnerBox. Now technically speaking which is the best method and why?

推荐答案

黄金法则是这样的:chrome 元素使用 id,content 元素使用 class.所以方法2更好.

The golden rules goes as this: use id for chrome elements, use class for content elements. So method 2 is the better.

您可以在 css-discuss 上阅读这篇文章以获得灵感:http://css-discuss.incutio.com/wiki/Classes_Vs_Ids

You can read this article on css-discuss for inspiration: http://css-discuss.incutio.com/wiki/Classes_Vs_Ids

没有什么可以阻止您在独特的内容元素上使用 id 属性,并且在某些情况下,它可能是加速 javascript DOM 遍历的好方法.然而,出于造型目的,它被许多人认为是不好的做法.

There is nothing that stops you from using id attributes on unique content elements, and in some cases it can be a nice way to speed up javascript DOM traversals. For styling purposes, however, it is considered by many as bad practice.

要考虑的要点是:

  1. 类可以用于多重继承,id必须是唯一的
  2. 如果您需要将继承与 id 样式配对使用,选择器的特殊性可能会成为一场噩梦

每当我在非 Chrome 元素上使用 id 属性时,它纯粹是为了快速访问 javascript,而不是为了样式.

Whenever I use id attributes on non-chrome elements it is purely for fast javascript access, and never for styling.

这篇关于哪种方法更好?CSS类或ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Each child in an array should have a unique key propquot; only on first time render of page(“数组中的每个孩子都应该有一个唯一的 key prop仅在第一次呈现页面时)
How do I make a TextGeometry multiline? How do I put it inside a square so it wraps like html text does inside a div?(如何制作 TextGeometry 多线?如何将它放在一个正方形内,以便它像 html 文本一样包裹在 div 内?) - IT屋-程序员软件开发技术分享社
Scale background image to fit ie8 window(缩放背景图像以适合 ie8 窗口)
@fontface in IE7 (IETEster) not working properly(IE7 (IETEster) 中的@fontface 无法正常工作)
Safari 5.1 breaks CSS table cell spacing(Safari 5.1 打破 CSS 表格单元格间距)
Put in bold part of description in metatag Drupal module(将描述的粗体部分放在元标记 Drupal 模块中)