What is a selector in CSS?
sobes.tech AI
Answer from AI
A CSS selector is a pattern that defines which HTML elements styles are applied to. It tells the browser which one or more elements to select.
There are different types of selectors:
-
Element selectors (Type selectors): Select all instances of an HTML element.
p { /* Selects all paragraphs */ color: blue; } -
Class selectors: Select elements with a specific
classattribute value..highlight { /* Selects all elements with class "highlight" */ background-color: yellow; } -
ID selectors: Select a single element with a specific
idattribute value.#header { /* Selects the element with id "header" */ font-size: 2em; } -
Universal selector: Selects all elements.
* { /* Selects all elements on the page */ margin: 0; padding: 0; } -
Attribute selectors: Select elements based on the presence or value of their attributes.
[type="text"] { /* Selects all input with type="text" */ border: 1px solid gray; } -
Pseudo-classes: Select elements based on their state.
a:hover { /* Selects link on hover */ text-decoration: underline; } -
Pseudo-elements: Select specific parts of an element or create "fictitious" elements.
p::first-line { /* Selects the first line of a paragraph */ font-weight: bold; } -
Combinators: Define relationships between selectors.
Combinator Description Example Space ( )Descendant selector div p>Child selector div > p+Adjacent sibling selector h1 + p~General sibling selector h1 ~ p
Selectors can be combined for more precise element targeting.