当涉及到CSS时,<div class="">和<div id="">之间有什么区别?是否可以使用<div id="">?

我看到不同的开发人员用这两种方式来做这件事,因为我是自学的,所以我从来没有真正弄清楚。


当前回答

CSS是面向对象的。ID表示实例,class表示类。

其他回答

在哪里使用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.

1) div id不可重用,只能应用于HTML的一个元素,而div类可以添加到多个元素中。

2)一个id更重要,如果两者都应用于同一个元素,并且有冲突的样式,id的样式将被应用。

3) Style元素总是引用div类。(点)在他们的名字前面,而div id类是通过在他们的名字前面放一个#(哈希)来引用的。

4)举例:-

<style>声明- .red-background {background-color:红色;} 在<style>声明- #blue-background {background-color:蓝色;} <div class="red-background" id="blue-background">Hello</div> 这里的背景将是蓝色的

在应用CSS时,将其应用于类,并尽量避免应用于id。ID只能在JavaScript中用于获取元素或任何事件绑定。

应该使用类来应用CSS。

有时必须使用类进行事件绑定。在这种情况下,尽量避免使用用于应用CSS的类,而是添加没有相应CSS的新类。当你需要更改任何类的CSS或更改任何元素的CSS类名时,这将会有所帮助。

或许打个比方有助于理解其中的区别:

<student id="JonathanSampson" class="Biology Calculus" />
<student id="MarySmith" class="Biology Networking" />

学生证是不同的。校园里不允许两个学生使用相同的学生证。然而,许多学生可以并且愿意与其他同学共享至少一个班级。

把多个学生放在一个班级标题下是可以的,比如生物。但把多个学生放在一个学号下是不可接受的。

当通过学校对讲系统发布规则时,你可以向一个班级发布规则:

“明天,所有的学生都要穿一件红衬衫去上生物课。”

.Biology {
  color: red;
}

或者你可以给一个特定的学生规则,通过调用他的唯一ID:

“乔纳森·桑普森明天要穿绿色衬衫。”

#JonathanSampson {
  color: green;
}

在这种情况下,乔纳森·桑普森收到了两个命令:一个是生物课上的学生,另一个是直接要求。因为通过id属性直接告诉Jonathan穿绿色衬衫,所以他将忽略先前穿红色衬衫的请求。

更具体的选择器获胜。

类用于具有公共属性的多个元素。例如,如果你想让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>

我们生成输出

输出