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

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


当前回答

在高级开发id中,我们可以使用JavaScript。

为了可重复的目的,类比id更方便,因为id应该是唯一的。

下面是一个例子来说明上面的表达:

<div id="box" class="box bg-color-red">this is a box</div>
<div id="box1" class="box bg-color-red">this is a box</div>

现在你可以在这里看到box和box1是两个(2)不同的<div>元素,但我们可以将box和bg- colour -red类应用于它们。

这个概念是面向对象语言中的继承。

其他回答

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

我们生成输出

输出

一个CLASS应该用于您希望具有相同样式的多个元素。ID应该用于唯一的元素。请参阅本教程。

如果您想成为一个严格的墨守成规者,或者如果您希望您的页面符合标准,那么您应该参考W3C标准。

任何元素都可以有类或id。

类用于引用某种类型的显示,例如,您可能有一个css类用于表示这个问题的答案的div。因为会有很多答案,多个div将需要相同的样式,你将使用一个类。

一个id只引用一个元素,例如右边的相关部分可能有特定于它的样式,而不是在其他地方重用,它将使用一个id。

从技术上讲,您可以使用所有的类,或者在逻辑上拆分它们。但是,您不能对多个元素重用id。

在CSS中,类选择器是一个以句号(“.”)开头的名称,ID选择器是一个以散列字符(“#”)开头的名称。ID和类之间的区别是,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.