在 CSS 中,我知道如果您定位一个唯一元素并使用类作为一组元素的一般定位,您可以使用 ID。我正在维护一个站点,我必须清理一些代码(html + css),我注意到以前的程序员没有为所有元素使用任何 ID,而是他使用类,即使是唯一元素。
所以,什么应该是一种可取的方法,我应该只使用类并遵循他的编码风格,避免对元素使用 ID,还是应该用 ID 替换它们并将 ID 用于适当的元素。
在 css 中,据我了解,类也可以像 ID 一样使用,您可以只针对单个元素(例如 .footer 与 #footer),这只是一个偏好问题。
#header { background: #ccc; height: 150px; }
#content { background: red; height: 200px; color: #fff; }
<div id="header"><h1>Header Area</h1></div>
<div id="content"><h1>Content</h1></div>
<div id="header"><h1>Footer Area</h1></div>
注意#header在 id 中被提及两次,并且 css 规则适用于这两个元素。
ID 的行为类似于类 ( http://jsfiddle.net/79GsY/ )
.header { background: #ccc; height: 150px; }
.content { background: red; height: 200px; color: #fff; }
.footer { background: brown; height: 150px; }
<div class="header"><h1>Header Area</h1></div>
<div class="content"><h1>Content</h1></div>
<div class="footer"><h1>Footer Area</h1></div>
请注意,这里没有使用 ID。
类的行为类似于 ID ( http://jsfiddle.net/qHEJd/ )
请赐教这个问题。谢谢你。