CSS Selectors
CSS (Cascading Style Sheets) selectors are patterns used to select and style HTML elements on a web page. Selectors allow you to target specific elements or groups of elements and apply styles to them. Here are some commonly used CSS selectors:
Type Selector: Selects elements based on their tag name. For example, to select all <h1>
elements, you would use h1
as the selector.
Class Selector: Selects elements based on their class attribute. To select elements with a specific class, use a dot (.
) followed by the class name. For example, to select all elements with the class “my-class”, use .my-class
as the selector.
ID Selector: Selects elements based on their ID attribute. To select an element with a specific ID, use a hash (#
) followed by the ID name. For example, to select an element with the ID “my-element”, use #my-element
as the selector.
Universal Selector: Selects all elements on the page. It is represented by an asterisk (*
). For example, *
selects all elements on the page.
Descendant Selector: Selects elements that are descendants of another element. It is represented by a space between two selectors. For example, ul li
selects all <li>
elements that are descendants of <ul>
elements.
Child Selector: Selects elements that are direct children of another element. It is represented by a greater-than sign (>
). For example, ul > li
selects all <li>
elements that are direct children of <ul>
elements.
Adjacent Sibling Selector: Selects an element that directly follows another element. It is represented by a plus sign (+
). For example, h2 + p
selects the <p>
element that directly follows an <h2>
element.
Attribute Selector: Selects elements based on their attribute values. There are several types of attribute selectors, such as [attr]
(selects elements with the specified attribute), [attr=value]
(selects elements with the specified attribute and value), and more.
Pseudo-class Selector: Selects elements based on a certain state or condition. Pseudo-classes are preceded by a colon (:
). Examples include :hover
(selects elements when hovered over), :first-child
(selects the first child element), :nth-child(n)
(selects the nth child element), and so on.
These are just a few examples of CSS selectors. CSS provides a wide range of selectors that allow you to target specific elements in a flexible and precise manner.