CSS Selectors are patterns used to target and style HTML elements. With CSS selectors, you can control colors, fonts, spacing, and layout by applying rules to specific parts of your webpage. Understanding selectors is essential for writing clean, efficient, and scalable CSS.
What Are CSS Selectors?
A CSS selector defines which HTML element(s) a style applies to. It is the first part of a CSS rule before the declaration block.
selector {
property: value;
}
Types of CSS Selectors
1. Element Selector
Targets HTML tags directly (e.g., p
, h1
, div
).
p {
color: blue;
font-size: 16px;
}
2. Class Selector
Targets elements with a specific class. Classes are reusable and prefixed with a dot (.
).
.highlight {
background-color: yellow;
padding: 5px;
}
3. ID Selector
Targets a single unique element with an ID, prefixed by a hash (#
).
#main-title {
text-align: center;
color: green;
}
4. Grouping Selector
Applies the same style to multiple elements by separating them with commas.
h1, h2, p {
font-family: Arial, sans-serif;
}
5. Universal Selector
Targets all elements on the page using an asterisk (*
).
* {
margin: 0;
padding: 0;
}
6. Attribute Selector
Targets elements based on their attributes and values.
input[type="text"] {
border: 1px solid #ccc;
padding: 8px;
}
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Selectors Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="main-title">Welcome to CSS Selectors</h1>
<p class="highlight">This paragraph is styled with a class selector.</p>
<input type="text" placeholder="Enter your name">
</body>
</html>
CSS (style.css):
#main-title {
color: darkblue;
}
.highlight {
background-color: yellow;
font-style: italic;
}
input[type="text"] {
border: 2px solid gray;
padding: 6px;
}
Why CSS Selectors Matter
Mastering CSS selectors allows developers to write less code while applying precise styles. They make styling more efficient, maintainable, and help build responsive designs.
Conclusion
CSS Selectors are the foundation of styling in web development. By using element, class, ID, group, universal, and attribute selectors, you can create powerful and flexible styles for modern websites.