Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




HTML - Id


An HTML id attribute is quite similar to class attribute with some minor differences(We will be discussing the differences later in this tutorial).


As the name suggests an HTML id is used to define a single ID for an HTML element. An HTML id name begins with a hash (i.e. #) followed by the id name.


Let us understand it with the below example :


Example :



<html>
	<head> 
		<style>
			#myID {
                border-style: dotted;
                border-width: 5px;
			}
		</style>
	</head>
	<body>
		<div id = "myID">
			<img src="image1.jpg" style = "width:100%">
        </div>
	</body>        
</html>


Output :




So, in the above example we have followed a set of tasks to use the id attribute. Let us see them below :

  1. We have used the id attribute with the <div> element and named it myID.


    HTML id

  2. We have defined a <head> element.



    <head>
    	...
    </head>

  3. Inside the <head> element we have defined a <style> element.



    <head>
    	<style>
    		...
    	</style>
    </head>

  4. Inside the <style> element we have defined the values of the id attribute.



    <head>
    	<style>
    		#myID {
    			border-style: dotted;
    			border-width: 5px;
    		}
    	</style>
    </head>

  5. Just remember, an id name starts with a '#'(i.e. '#myID'). And the values of the class are placed inside braces(i.e. '{}')


In words, we give a to the id attribute(myID in this case).


<div id = "myID">

And define the values of the class inside the <style> attribute.


<style>
	#myID {
		border-style: dotted;
		border-width: 5px;
	}
</style>

The id is created using a hash (i.e. #) followed by the id name (i.e. #myID). Post which you can define the values inside the braces(i.e. {}).


#myID {
	border-style: dotted;
	border-width: 5px;
}

Next, let us see the difference between the id and class attribute.


Difference between id and class attribute in HTML


An id attribute begins with a hash (i.e. #) followed by the id name.


#myID {
	border-style: dotted;
	border-width: 5px;
}

Whereas a class attribute begins with a dot (i.e. .) followed by the class name.


.myClass {
	border-style: dotted;
	border-width: 5px;
}

An id attribute can be used with only one HTML element.


<html>
<head>
	<style>
		#myID {
			border-style: dotted;
			border-width: 5px;
		}
	</style>
</head>
<body>
	<div id = "myID">
		<img src="image1.jpg">
	</div>
</html>

Whereas a class attribute can be used with multiple HTML elements.


<html>
<head>
<style>
	.myClass {
		width:40%;
		display:inline-block;
	}
</style>
</head>
<body>
	<div class = "myClass">
		<img src="image1.jpg">
	</div>
	<div class = "myClass">
		<img src="image2.jpg">
	</div>
</body>
</html>