I'm new to HTML / CSS coding and since I first bumped into the ID and class selector, one question has been running through my mind. I searched the web thoroughly over and over again, but I coudln't find the answer I was looking for.
The question is : Why use ID when you can do the same task with class ?
I mean, ok I know that ID's are just for one time use and classes are for many, but what forbids me from using the class selector for just once ? So, according to this, what is the purpose of existence of ID's in CSS ?
Furthermore, what do we need ID's and even classes for, when we can make a new element in the stylesheet with exactly the same attributes ?
The following code is an example of what I'm trying to ask :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ID's, classes and new elements</title>
<style>
#sidebar1 {
display: block;
background-color: yellow;
width: 200px;
height: 500px;
margin-right: 50px;
float: left;
}
.sidebar2 {
display: block;
background-color: yellow;
width: 200px;
height: 500px;
margin-right: 50px;
float: left;
}
new_element {
display: block;
background-color: yellow;
width: 200px;
height: 500px;
margin-right: 50px;
float: left;
}
</style>
</head>
<body>
<div id="sidebar1">What is the difference?</div><!--Use of ID selector-->
<div class="sidebar2">What is the difference?</div><!--Use of class selector just once !-->
<new_element>What is the difference?</new_element><!--Use of a new made element with exactly the same attributes-->
</body>
</html>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…