Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Difference between dot (.) and hash(# )selector in CSS
In CSS, the dot (.) and hash (#) selectors are used to apply styles to HTML elements. The dot selector targets elements by their class attribute, while the hash selector targets a specific element by its id attribute.
Dot (.) Selector − Class Selector
The . (dot) selector is a class-level selector. It creates a style class that can be applied to multiple HTML elements. Any element with the matching class attribute will receive the style.
.blackBorder {
border: 2px solid black;
}
This style applies to every element that has class="blackBorder".
Hash (#) Selector − ID Selector
The # (hash) selector is an element-level selector. It applies a style to a single, unique element whose id attribute matches the selector. Each id must be unique within a page.
#redDiv {
border: 2px solid red;
}
This style applies only to the element with id="redDiv".
Key Differences
| Feature | . (Dot) Selector | # (Hash) Selector |
|---|---|---|
| Targets | class attribute | id attribute |
| Applies To | Multiple elements | One unique element |
| Specificity | Lower (10) | Higher (100) |
| Reusability | Reusable across many elements | Unique per page |
| Syntax | .className { } |
#idName { } |
Example
The following example shows the dot selector applied to multiple divs and the hash selector applied to one specific div ?
<!DOCTYPE html>
<html>
<head>
<title>Selector Example</title>
<style>
.blackBorder {
border: 2px solid black;
padding: 8px;
margin: 5px;
}
#redDiv {
border: 2px solid red;
padding: 8px;
margin: 5px;
}
</style>
</head>
<body>
<div>No Border Box</div>
<div class="blackBorder">Black Border Box (.class)</div>
<div id="redDiv">Red Border Box (#id)</div>
<div>No Border Box</div>
<div class="blackBorder">Black Border Box (.class)</div>
</body>
</html>
In the output, the two divs with class="blackBorder" both get black borders (class can be reused), while only the single div with id="redDiv" gets a red border (id is unique).
Conclusion
Use the dot (.) selector for reusable styles that apply to multiple elements, and the hash (#) selector for unique styles targeting a single specific element. The hash selector has higher specificity, so it overrides class styles when both apply to the same element.
