Selectors in CSS:
CSS selectors are patterns used to select and style HTML elements. They allow you to target specific elements or groups of elements within a web page, enabling you to apply styles based on various criteria.
Basic Selectors:
- Type Selector:
- Selects all elements of a specific type.
p {
/* Styles for all <p> elements */
color: blue;
}
- Class Selector:
- Selects elements with a specific class attribute.
.my-class {
/* Styles for elements with class="my-class" */
font-weight: bold;
}
- ID Selector:
- Selects a single element with a specific ID attribute.
#my-id {
/* Styles for element with id="my-id" */
background-color: yellow;
}
Attribute Selectors:
- Attribute Presence Selector:
- Selects elements with a specific attribute.
[type] {
/* Styles for elements with a "type" attribute */
border: 1px solid black;
}
- Attribute Value Selector:
- Selects elements with a specific attribute value.
[type="text"] {
/* Styles for elements with type="text" */
background-color: lightgray;
}
Combined Selectors:
- Descendant Selector:
- Selects elements that are descendants of a specified element.
div p {
/* Styles for <p> elements inside <div> elements */
margin-top: 10px;
}
- Child Selector:
- Selects elements that are direct children of a specified element.
ul > li {
/* Styles for <li> elements that are direct children of <ul> */
list-style-type: none;
}
- Adjacent Sibling Selector:
- Selects an element that is immediately preceded by a specified element.
h2 + p {
/* Styles for <p> elements immediately preceded by <h2> */
font-style: italic;
}
Pseudo-classes and Pseudo-elements:
- Pseudo-classes:
- Select elements based on their state or position.
a:hover {
/* Styles for <a> elements on hover */
color: red;
}
- Pseudo-elements:
- Select and style a specific part of an element.
p::first-line {
/* Styles for the first line of <p> elements */
font-weight: bold;
}
Combinators:
- Descendant Combinator (Space):
- Selects all elements that are descendants of a specified element.
div p {
/* Styles for <p> elements inside <div> elements */
margin-top: 10px;
}
- Child Combinator (>):
- Selects all elements that are direct children of a specified element.
ul > li {
/* Styles for <li> elements that are direct children of <ul> */
list-style-type: none;
}
- Adjacent Sibling Combinator (+):
- Selects an element that is immediately preceded by a specified element.
h2 + p {
/* Styles for <p> elements immediately preceded by <h2> */
font-style: italic;
}
- General Sibling Combinator (~):
- Selects elements that are siblings of a specified element.
h2 ~ p {
/* Styles for <p> elements that are siblings of <h2> */
font-weight: normal;
}
Understanding and practicing with these CSS selectors and their usage will enhance your ability to style web pages effectively.