CSS class - Difference Between CSS class vs CSS ID
CSS class is a selector to assign class name either one or group of element and apply specific styles.
Using class selector you can easily modify element styles.
CSS class selector define using class attribute with value (user define class name).
CSS class selector identify using (".") dot sign concatenate with user define class name.
CSS Class use for when you using JavaScript its identify of element using getElementByIClass() function.
CSS class advantages
One or more CSS class assign to a every single element separate by single space.
Another advantages is assign same class one or more element with same styles.
Syntax
If you assign same class name multiple element syntax is like,
.class_name { property: value; }
Example
<!DOCTYPE html>
<html>
<head>
<title>CSS elements with same class name</title>
<style>
.line {
color: #FFF;
font-size: 20px;
background-color: #FF6633;
}
</style>
</head>
<body>
<p class="line">This is a first paragraph.</p>
<div class="line">This is a first section.</div>
</body>
</html>
Syntax
CSS Class allows you to set a particular style for any HTML elements using CSS class. If you assign same class multiple element with assign unique style each element, syntax is like,
element.class_name { property:value; }
Example
<!DOCTYPE html>
<html>
<head>
<title>CSS elements with same class name with different style</title>
<style>
p.line {
color: #FF6633;
margin-left: 20px;
}
div.line {
color: #FFF;
font-size: 20px;
background-color: #FF6633;
}
</style>
</head>
<body>
<p class="line">This is a first paragraph.</p>
<div class="line">This is a first section.</div>
</body>
</html>
Complex Class Syntax
Following is complex example, in this example 3 different class name assign to the elements, Now we apply to the CSS style. Some CSS style are common and some or unique so lets see how to assign CSS style.
Example
<!DOCTYPE html>
<html>
<head>
<title>CSS class</title>
<style>
.line_1, .line_2, .ine_3{
font-size:16px;
}
.line_1 {
color: purple;
margin-left: 20px;
}
.line_2 {
font-size: 20px;
background-color: #FF6633;
}
.line_3 {
font-style: italic;
font-weight: bold;
}
</style>
</head>
<body>
<p class="line_1">This is a first paragraph.</p>
<div class="line_2">This is a first section.</div>
<div class="line_3">This is a second section.</div>
</body>
</html>
CSS class vs CSS ID
This difference is important to know where is use CSS ID and CSS Class. Because both work are same. CSS ID is a use for "unique identifier an element". It means CSS ID selector can be called only one times in a document while class selector can be called multiple times in a document.
But you can use Class have a maximum flexibility. Class and ID have not any strong rules to where is use CSS ID or CSS Class.
- CSS ID: Unique Personally Identification(ID) in Number of ID's.
- CSS Class: Multiple Identification in Number of Class.