Using HTML ID and Class

08/10/2022
HTML ID ve CSS Farkı

What should be considered when using ID and Class of HTML tags when designing a web page?

ID

The tag with the ID can be accessed with the “href” feature in order to go to the area where the ID is located in another part of the page.

<!DOCTYPE html>
<html> 
<head></head> 
<body> 
<a href="#click">Buton</a> 
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p> 
<!-- . . . --> 
<!-- . . . --> 
<!-- . . . --> 
<!-- . . . --> 
<!-- . . . --> 
<!-- . . . --> 
<p id="click">Dolor sit amet consectetur adipisicing elit.</p> 
</body> 
</html>

1 of a specific ID tag should be used in an HTML page. The same ID variable can be repeated on different pages.

If a specific HTML tag is to be triggered with Javascript, the use of ID is more accurate. (The HTML tag can also be triggered with the Class tag, ID is more preferred.)

<!DOCTYPE html>
<html> 
<head></head> 
<body> <button onclick="onclickFunction()">Test</button> 
<p id="text">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> 
<script> 
function onclickFunction() { 
document.getElementById("text").style.color = "red"; 
} 
</script>
</body> 
</html>

Class

Class should be used if more than one HTML tag will be given the same CSS properties.

HTML Class and ID Usage Differences

A class can be used in more than one HTML tag on a web page, but ID can only be used in 1 HTML tag.

<!DOCTYPE html>
<html>
<head></head> 
<body> 
<section id="section1" class="section"> 
</section> 
<section id="section2" class="section"> 
</section> 
<section id="section3" class="section"> 
</section> 
</body>
</html>

In the use of Internal and External CSS, “.” at the beginning of the CSS variable given to the Class while defining the CSS. character is used, “#” character is used in ID.

<!DOCTYPE html>
<html>
<head>
<style>
#id {
color: blue;
}
.class {
color: brown;
}
</style>
</head>
<body>
<p id="id">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
<p class="class">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</body>
</html>

Source:

https://www.w3schools.com/