There are five types of selectors are there:
• Simple Selector
• Combinator Selector
• Pseudo-class Selector
• Pseudo-element Selector
• Attribute Selector
Simple Selectors:
- Simple selectors are used to select HTML elements based on their element name, class, ID, or all elements.
There are 4 main types of simple selectors:
1.Element Selector – Selects elements by their tag name.
p {
color: blue;
}
2.Class Selector – Selects elements using the class attribute. It starts with ..
.box {
color: red;
}
3.ID Selector – Selects an element using the id attribute. It starts with #.
#header {
color: green;
}
4.Universal Selector – Selects all HTML elements. It is represented by *.
* {
margin: 0;
}
Combinator Selectors
- Combinator selectors are used to select HTML elements based on the relationship between two or more elements.
There are 4 main types:
1.Descendant Selector ( ) – Selects all elements inside another element.
div p {
color: blue;
}
2.Child Selector (>) – Selects only the direct children of an element.
div > p {
color: red;
}
3.Adjacent Sibling Selector (+) – Selects the element immediately following another element.
h1 + p {
color: green;
}
4.General Sibling Selector (~) – Selects all sibling elements that come after another element.
h1 ~ p {
color: orange;
}
Pseudo-class Selectors
- Pseudo-class selectors are used to select an element based on its state, condition, or position.
- They are written using a single colon (:).
Common pseudo-classes:
• :hover – Applies styles when the mouse pointer is over an element.
• :focus – Applies styles when an element receives focus.
• :active – Applies styles when an element is being clicked.
• :first-child – Selects the first child element.
• :last-child – Selects the last child element.
• :nth-child() – Selects elements based on their position.
Pseudo-element Selectors
- Pseudo-element selectors are used to style a specific part of an HTML element rather than the entire element.
- They are written using a double colon (::).
Common pseudo-elements:
• ::before – Inserts content before an element.
• ::after – Inserts content after an element.
• ::first-letter – Styles the first letter of an element.
• ::first-line – Styles the first line of an element.
• ::selection – Styles the text selected by the user.
Attribute Selectors
- Attribute selectors are used to select HTML elements based on their attributes or attribute values.
- They are written using square brackets [].
Example
input[type="text"] {
border: 1px solid blue;
}
Here, input[type="text"] selects only elements whose type attribute is "text".
The CSS style is applied only to the text input.
Top comments (0)