Thursday, January 10, 2019

CSS: frequently used selectors

Basic selectors 

Wildcard selector: selects all elements
* {}
Type selector: selects all elements of the given type
div {}
Attribute selector ([]): selects all elements that has the given attribute
[src] {}
ID selector (#): selects the element with the given ID attribute
#menu {} /* or [id="menu"] {} */
Class selector (.): selects all elements with the given class attribute
.centered {} /* or [class~="centered"] {} */

Selector grouping

selector grouping (,): enables to specify common values in one place
div, #menu, .centered {}

Selector chaining

Selector chaining
div.#menu.centered[name="Menu"]:first-child::first-letter {}

Attribute value selectors

[attribute="value"] selector: selects all elements with the specified attribute and value
[target="_blank"] {}
[attribute~="value"] selector: selects all elements whose attribute value contains the specified whole word.
[title~="flower"] {}
[attribute|="value"] selector: selects all elements whose attribute value starts with the specified value, the value being a whole word or the first part of a hyphenated word.
[class|="top"] {}
[attribute^="value"] selector: selects all elements whose attribute value begins with the specified value. (like in regex)
[class^="top"] {}
[attribute$="value"] selector: selects all elements whose attribute value ends with the specified value. (like in regex)
[class$="test"] {}
[attribute*="value"] selector: selects all elements whose attribute value contains the specified value.
[class*="te"] {}

Selector combination

Descendant selector (space): matches all elements that are descendants of a specified element
div p {}
Child selector (>): selects all elements that are the immediate children of a specified element
div > p {}
Adjacent sibling selector (+): selects all elements that are the adjacent siblings of a specified element
div + p {}
General sibling selector (~): selects all elements that are siblings of a specified element
div ~ p {}

No comments:

Post a Comment