π― CSS Selectors: The Ultimate Guide
CSS selectors are the foundation of styling in web development. They allow you to target HTML elements and apply styles to them. Letβs explore the major types of selectors and how to use them effectively.
π§± 1. Basic Selectors
These are the most commonly used selectors in CSS.
πΉ Element Selector
Targets all elements of a specific type.
p {
color: blue;
font-size: 16px;
}
β
All <p>
tags will be styled with blue text.
πΉ Class Selector (.class)
.box {
background-color: lightgray;
padding: 20px;
}
β
Any element with class="box"
will get the styles.
πΉ ID Selector (#id)
#header {
font-size: 24px;
text-align: center;
}
β
Only the element with id="header"
will be affected.
π§© 2. Group & Universal Selectors
πΉ Universal Selector (*)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
β Useful for resetting default browser styles.
πΉ Group Selector (element1, element2)
h1, h2, h3 {
font-family: Arial, sans-serif;
color: darkgreen;
}
β All headings will share the same style.
π 3. Combinators
Combinators define relationships between elements.
πΉ Descendant Selector (space)
nav a {
color: navy;
}
β
All <a>
tags inside <nav>
will be styled.
πΉ Child Selector (>)
ul > li {
list-style-type: square;
}
β
Only direct <li>
children of <ul>
will be affected.
πΉ Adjacent Sibling (+)
h2 + p {
font-style: italic;
}
β
Only the first <p>
after an <h2>
will be styled.
πΉ General Sibling (~)
h2 ~ p {
color: gray;
}
β
All <p>
elements after an <h2>
will be affected.
π§ͺ 4. Attribute Selectors
These selectors target elements based on their attributes.
πΉ Exact Match
input[type="text"] {
border: 1px solid black;
}
β
Only <input>
elements with type="text"
will be styled.
πΉ Starts With (^=)
a[href^="https"] {
color: green;
}
β All links that start with https will be green.
πΉ Ends With ($=)
img[src$=".jpg"] {
border-radius: 10px;
}
β All .jpg images will have rounded corners.
πΉ Contains (*=)
div[class*="card"] {
box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
β Any class that contains "card" will get a shadow.
π» Using These in VS Code
π§Ύ HTML Example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="main-title">Welcome</h1>
<div class="box card">
<p>This is a styled box.</p>
</div>
<nav>
<a href="https://example.com">Home</a>
<a href="http://example.com">About</a>
</nav>
<input type="text" placeholder="Enter name">
</body>
</html>
π¨ CSS Example (style.css)
/* Basic Selectors */
h1 {
color: crimson;
}
.box {
background-color: lightblue;
}
#main-title {
font-size: 32px;
}
/* Group & Universal */
* {
margin: 0;
padding: 0;
}
h1, p {
font-family: sans-serif;
}
/* Combinators */
nav a {
text-decoration: none;
}
nav > a {
font-weight: bold;
}
h1 + div {
border: 2px solid black;
}
/* Attribute Selectors */
input[type="text"] {
padding: 10px;
}
a[href^="https"] {
color: green;
}