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
-
Economics & Finance
Selected Reading
What is a CSS Selector?
CSS selectors are patterns used to select and style HTML elements. They act as a bridge between your HTML structure and CSS styles, allowing you to target specific elements or groups of elements on your webpage.
Syntax
selector {
property: value;
}
Types of CSS Selectors
| Selector Type | Syntax | Description |
|---|---|---|
| Element Selector | p |
Selects all elements of a specific type |
| Class Selector | .demo |
Selects all elements with class="demo" |
| ID Selector | #myid |
Selects the element with id="myid" |
| Universal Selector | * |
Selects all elements on the page |
Example: Class Selector
The following example demonstrates how to use a class selector to style multiple elements −
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
padding: 10px;
margin: 5px;
}
</style>
</head>
<body>
<p class="highlight">This paragraph has the highlight class.</p>
<div class="highlight">This div also has the highlight class.</div>
<p>This paragraph has no class applied.</p>
</body>
</html>
Two elements (paragraph and div) appear with yellow background and padding, while the third paragraph remains unstyled.
Example: ID Selector
The following example shows how to target a specific element using an ID selector −
<!DOCTYPE html>
<html>
<head>
<style>
#header {
color: blue;
font-size: 24px;
text-align: center;
}
</style>
</head>
<body>
<h1 id="header">Main Header</h1>
<h1>Regular Header</h1>
</body>
</html>
The first header appears in blue color, 24px font size, and centered alignment, while the second header remains with default styling.
Conclusion
CSS selectors are essential for targeting HTML elements. Class selectors target multiple elements with the same class, ID selectors target unique elements, and element selectors target all elements of a specific type.
Advertisements
