CSS Selectors

CSS Selectors

To select DOM elements in CSS using selector.

Tag Selector

a {
  color: black;
}

h1 {
  font-size 24px;
}

Single selector

Selector Description
article Selects the element with the article tag
.post Selects all elements with the post class
#nav Selects the elements with the nav Id
div.row Selects all elements with the div tag and the row class
[hidden="true"] Selects all elements with the hidden attribute with a value of true

Note: Wildcard selector can be used to select all DOM elements.

Combine selector

Selector Description
div li DOM descendant combinator. All li tags that are a child of div tags
div.row * Selects all elements that are descendant (or child) of the elements with div tag and row class
div > li Difference combinator. Select direct descendants
div + li the adjacent combinator. It selects the element that is immediately preceded by the former element. In this case, only the first li after each div.
div, li Selects all li elements and all div elements.
div - li The sibling combinator. Selects li element following a div element.

Pseudo-selectors

Position of an element

Selector Description
:first-child Target the first element immediately inside (or child of) another element
:last-child Target the last element immediately inside (or child of) another element
:nth-child() Target the nth element immediately inside (or child of) another element. Admits integers, even, odd, or formulas
div:not(.name) Selects all div elements that are not of the .name class
::after Allows inserting content onto a page from CSS, instead of HTML. While the end result is not actually in the DOM, it appears on the page as if it is. This content loads after HTML elements.
::before Allows inserting content onto a page from CSS, instead of HTML. While the end result is not actually in the DOM, it appears on the page as if it is. This content loads before HTML elements.

State of an element

Selector Description
:hover selects an element that is being hovered by a mouse pointer
:focus selects an element receiving focus from the keyboard or programattially
:active selects an element being clicked by a mouse pointer
:link selects all links that have not been clicked yet
:visited selects a link that has already been clicked

Example

The :nth-child can use pattern, such as odd, even, An+B

a:nth-child(3n) {
  /* Css goes here */
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


The reCAPTCHA verification period has expired. Please reload the page.