Selector In CSS
Hello guys today we discuss about css selector:
CSS selectors are the patterns used to "select" the HTML elements you want to style. They are the fundamental link between your HTML structure and your CSS rules.
Here is a breakdown of the most common types of selectors, ranging from simple to complex.
1. Basic Selectors
These are the most common ways to target elements.
* Universal Selector (*)
Selects all elements on the page.
* {
box-sizing: border-box;
}
Selects all elements of a specific HTML tag name.
p {
color: blue;
}
* Class Selector (.)
Selects all elements that have a specific class attribute. This is the most versatile selector.
.button {
background-color: red;
}
* ID Selector (#)
Selects a single element with a specific unique ID.
#header {
height: 100px;
}
2. Grouping Selector
If multiple elements share the same style, you can group them with a comma to save space.
h1, h2, p {
font-family: Arial, sans-serif;
}
3. Combinators
These selectors target elements based on their relationship to other elements in the HTML structure.
* Descendant Selector (space)
Selects an element that is nested anywhere inside a specified element.
div p {
color: green;
}
* Child Selector (>)
Selects an element that is a direct child of a specified element (no levels in between).
ul > li {
list-style: none;
}
Selects an element that comes immediately after another specific element.
h1 + p {
margin-top: 0;
}
4. Pseudo-classes (:)
These select elements based on a specific state.
:hover – When the user mouses over an element.
:focus – When an element is selected (like clicking into an input field).
:nth-child() – Selects elements based on their position in a list.
a:hover {
text-decoration: underline;
}
li:nth-child(2) {
color: red;
}
5. Pseudo-elements (::)
These style a specific part of an element.
::before – Inserts content before the element's content.
::after – Inserts content after the element's content.
::first-line – Styles only the first line of text.
p::first-line {
font-weight: bold;
}
Selects elements based on the presence or value of an attribute (like type, href, src, etc.).
Targets input fields where type="text"
input[type="text"] {
border: 1px solid gray;
}
Targets links that contain ".pdf"
a[href$=".pdf"] {
color: red;
}
Specificity Note
When multiple selectors target the same element, the browser uses Specificity to decide which rule wins. generally:
IDs > Classes > Tags
For example, if you have .red-text { color: red; } and p { color: blue; },
a paragraph with that class will be red because a class is more specific than a tag.
Comments
Post a Comment