CSS Selectors: A Complete Guide to Styling Web Pages
CSS selectors are the foundation of styling in web development, allowing you to target specific HTML elements and apply styles. Understanding CSS selectors is essential for creating visually appealing and responsive web pages. In this guide, we’ll explore what CSS selectors are, their types, and best practices for using them effectively.
What Are CSS Selectors?
CSS selectors define the rules for selecting HTML elements that you want to style. They act as a bridge between your HTML structure and CSS rules, enabling precise and efficient styling.
Basic Types of CSS Selectors
Group Selector (,
)
- Targets multiple elements at once.
h1, h2, h3 {
font-family: Arial, sans-serif;
}
ID Selector (#id
)
- Targets a single element with a specific ID.
#main {
width: 100%;
}
Class Selector (.classname
)
- Targets elements with a specific class.
.highlight {
background-color: yellow;
}
Type Selector (Element Selector)
- Targets elements by their HTML tag.
p {
font-size: 16px;
}
Universal Selector (*
)
- Targets all elements on a page.
* {
margin: 0;
padding: 0;
}
Advanced CSS Selectors
General Sibling Selector (~
)
- Targets all siblings of a specified element.
h1 ~ p {
color: blue;
}
Adjacent Sibling Selector (+
)
- Targets an element immediately following another.
h1 + p {
margin-top: 10px;
}
Child Selector (>
)
- Targets direct children of a parent element.
ul > li {
list-style: none;
}
Descendant Selector (Space)
- Targets elements nested inside a parent element.
div p {
color: gray;
}
Attribute Selector
- Targets elements based on their attributes.
input[type="text"] {
border: 1px solid #ccc;
}
Pseudo-Classes and Pseudo-Elements
Pseudo-Classes
Define a special state of an element.
a:hover {
color: red;
}
Common pseudo-elements include:
:hover
: When an element is hovered over.
:focus
: When an element gains focus.
:nth-child(n)
: Targets elements based on their position in the DOM.
Pseudo-Elements
Style specific parts of an element.
p::first-line {
font-weight: bold;
}
Common pseudo-classes include:
::before
::after
::first-letter
Combinators in CSS Selectors
General Sibling Combinator (~
)
- Selects all siblings after a specified element.
h1 ~ p {
color: green;
}
Adjacent Sibling Combinator (+
)
- Selects the first sibling that comes immediately after.
h1 + p {
font-style: italic;
}
Child Combinator (>
)
- Selects immediate child elements.
div > p {
text-align: justify;
}
Descendant Combinator (Space)
- Selects elements inside another element.
div p {
font-size: 14px;
}
Special CSS Selectors
Only Child (:only-child
)
- Selects an element that is the only child of its parent.
p:only-child {
font-size: 18px;
}
Empty Selector (:empty
)
- Selects elements with no children.
div:empty {
display: none;
}
Not Selector (:not()
)
- Excludes elements from the selection.
p:not(.special) {
color: black;
}