CSS
Beginner
CSS Selectors and Specificity
84 views
45 min read
Table of Contents
Understanding CSS Selectors
CSS selectors are patterns used to select and style HTML elements. Understanding selectors is crucial for effective CSS styling.
Basic Selectors
Element Selector
p {
color: blue;
}
/* Selects all <p> elements */
Class Selector
.highlight {
background-color: yellow;
}
/* Selects elements with class="highlight" */
ID Selector
#header {
font-size: 24px;
}
/* Selects element with id="header" */
Advanced Selectors
Descendant Selector
div p {
margin: 10px;
}
/* Selects all <p> elements inside <div> elements */
Child Selector
ul > li {
list-style-type: none;
}
/* Selects direct <li> children of <ul> */
Pseudo-classes
a:hover {
color: red;
}
input:focus {
border: 2px solid blue;
}
li:first-child {
font-weight: bold;
}
CSS Specificity
Specificity determines which CSS rule applies when multiple rules target the same element:
- Inline styles: 1000 points
- IDs: 100 points
- Classes, attributes, pseudo-classes: 10 points
- Elements and pseudo-elements: 1 point
Practical Example
<style>
/* Specificity: 1 */
p {
color: black;
}
/* Specificity: 10 */
.intro {
color: blue;
}
/* Specificity: 100 */
#main-text {
color: red;
}
/* Specificity: 11 */
.intro p {
color: green;
}
</style>
<p class="intro" id="main-text">What color will this be?</p>
<!-- Answer: Red (ID has highest specificity) -->