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

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


当前回答

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> 这里的背景将是蓝色的

其他回答

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表示实例,class表示类。

id是唯一的。不类。元素也可以有多个类。类也可以动态地添加和删除到元素中。

任何可以使用ID的地方都可以使用类。反之则不然。

惯例似乎是对每个页面上的页面元素使用id(如“导航栏”或“菜单”),对其他所有元素使用类,但这只是惯例,你会发现使用上的差异很大。

另一个区别是,对于表单输入元素,<label>元素通过ID引用字段,因此如果要使用<label>,则需要使用ID。是一个可访问性的东西,你真的应该使用它。

在过去的岁月里,id也是首选,因为它们很容易在Javascript中访问(getElementById)。随着jQuery和其他Javascript框架的出现,现在这几乎不是一个问题。

在哪里使用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中,我们可以使用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类应用于它们。

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