当涉及到CSS时,<div class="">和<div id="">之间有什么区别?是否可以使用<div id="">?
我看到不同的开发人员用这两种方式来做这件事,因为我是自学的,所以我从来没有真正弄清楚。
当涉及到CSS时,<div class="">和<div id="">之间有什么区别?是否可以使用<div id="">?
我看到不同的开发人员用这两种方式来做这件事,因为我是自学的,所以我从来没有真正弄清楚。
当前回答
在哪里使用ID而不是类
两者之间的简单区别是,虽然类可以在页面上重复使用,但ID在每个页面上只能使用一次。因此,在标记页面主要内容的div元素上使用一个ID是合适的,因为将只有一个主要内容部分。相反,您必须使用一个类来设置表上的交替行颜色,因为根据定义,它们将被使用不止一次。
IDs are an incredibly powerful tool. An element with an ID can be the target of a piece of JavaScript that manipulates the element or its contents in some way. The ID attribute can be used as the target of an internal link, replacing anchor tags with name attributes. Finally, if you make your IDs clear and logical, they can serve as a sort of “self documentation” within the document. For example, you do not necessarily need to add a comment before a block stating that a block of code will contain the main content if the opening tag of the block has an ID of, say, "main", "header", "footer", etc.
其他回答
id在整个页面中必须是唯一的。
一个类可以应用于许多元素。
有时候,使用id是个好主意。
在一个页面中,你通常有一个页脚,一个页眉…
然后页脚可以是一个带有id的div
<div id="footer" class="…"" >
而且还有课
id是唯一的。不类。元素也可以有多个类。类也可以动态地添加和删除到元素中。
任何可以使用ID的地方都可以使用类。反之则不然。
惯例似乎是对每个页面上的页面元素使用id(如“导航栏”或“菜单”),对其他所有元素使用类,但这只是惯例,你会发现使用上的差异很大。
另一个区别是,对于表单输入元素,<label>元素通过ID引用字段,因此如果要使用<label>,则需要使用ID。是一个可访问性的东西,你真的应该使用它。
在过去的岁月里,id也是首选,因为它们很容易在Javascript中访问(getElementById)。随着jQuery和其他Javascript框架的出现,现在这几乎不是一个问题。
一个CLASS应该用于您希望具有相同样式的多个元素。ID应该用于唯一的元素。请参阅本教程。
如果您想成为一个严格的墨守成规者,或者如果您希望您的页面符合标准,那么您应该参考W3C标准。
在哪里使用ID而不是类
两者之间的简单区别是,虽然类可以在页面上重复使用,但ID在每个页面上只能使用一次。因此,在标记页面主要内容的div元素上使用一个ID是合适的,因为将只有一个主要内容部分。相反,您必须使用一个类来设置表上的交替行颜色,因为根据定义,它们将被使用不止一次。
IDs are an incredibly powerful tool. An element with an ID can be the target of a piece of JavaScript that manipulates the element or its contents in some way. The ID attribute can be used as the target of an internal link, replacing anchor tags with name attributes. Finally, if you make your IDs clear and logical, they can serve as a sort of “self documentation” within the document. For example, you do not necessarily need to add a comment before a block stating that a block of code will contain the main content if the opening tag of the block has an ID of, say, "main", "header", "footer", etc.
类用于具有公共属性的多个元素。例如,如果你想让p和body标签的颜色和字体相同,使用class属性或在一个除法本身。
另一方面,Id用于突出显示单个元素属性,并且仅用于特定元素。例如,我们有一个带有某些属性的h1标签,我们不希望它们在整个页面的任何其他元素中重复。
需要注意的是,如果在元素中同时使用class和id,则*id将覆盖class属性。*因为id只用于单个元素
参考下面的例子
<html>
<head>
<style>
#html_id{
color:aqua;
background-color: black;
}
.html_class{
color:burlywood;
background-color: brown;
}
</style>
</head>
<body>
<p class="html_class">Lorem ipsum dolor sit amet consectetur adipisicing
elit.
Perspiciatis a dicta qui unde veritatis cupiditate ullam quibusdam!
Mollitia enim,
nulla totam deserunt ex nihil quod, eaque, sed facilis quos iste.</p>
</body>
</html>
我们生成输出
输出