4

CSS Selectors: A Visual Guide

 1 year ago
source link: https://fffuel.co/css-selectors/?ref=sidebar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

* universal selector

Select all elements:

div * {
  background: coral;
}

element element selector

Select element(s):

p {
  background: deeppink;
}

.class class selector

Select all elements with the specified class name:

.my-class {
  background: royalblue;
}

#id ID selector

Select the element with the specified ID:

#my-id {
  background: aquamarine;
}

.class.class-2 multiple selectors

Chain two or more classes or IDs to select the element(s) that have all the specified classes/IDs:

.my-class.special {
  background: royalblue;
}

.class, .class-2 comma combinator

Separate multiple selector declarations using a comma. This makes it easy to apply the same styles to multiple selector declarations:

.item-1, .item-2 {
  background: sandybrown;
}

.class .class-2 descendant selector

Leave a space (descendant combinator) between selectors to select element(s) that are descendant of another element:

.wrapper .card {
  background: lightblue;
}

.class + .class-2 adjacent selector

Use a plus sign (adjacent combinator) to select an element that is a direct sibling to a first element:

.item-1 + div {
  background: yellowgreen;
}

.class > .class-2 child selector

Use a > sign (child combinator) to select element(s) that are direct children to another element:

.wrapper > div {
  background: olive;
}

.class ~ .class-2 general sibling selector

Use a tilde sign (general sibling combinator) to select every element that is preceded by the first element, without having to be a direct sibling to the first element:

.item-1 ~ div {
  background: lightcoral;
}

* + * lobotomized owl

A selector pattern known as the lobotomized owl where all elements that have a preceding sibling are selected. Use it for example to add spacing to elements within a container except for the first element, which has no preceding sibling.

Note that now that we have the :not() pseudo-class, we can select the same elements using :not(:first-child):

* + * {
  background: khaki;
}

[attr] attribute selector

Select element(s) that have a specified attribute:

[data-text] {
  background: deepskyblue;
}

[attr=val] attribute & attribute value

Select element(s) that have the specified attribute and attribute value:

[data-text="hello"] {
  background: lemonchiffon;
}

[attr~=val] attribute & one of the attribute's values

Select element(s) that have the specified attribute with one of it's space-separated values matching the value:

[title~="old"] {
  background: crimson;
}

[attr*=val] attribute & partial value

Select element(s) that have the specified attribute with val being included in the attribute value:

[title*="saur"] {
  background: darkgoldenrod;
}

[attr^=val] attribute & starting value

Select element(s) that have the specified attribute with a value that starts with val:

a[href^='http'] {
  background: Aquamarine;
}
a[href^='#'] {
  background: AntiqueWhite;
}
a[href^='/'] {
  background: LavenderBlush;
}

[attr$=val] attribute & ending value

Select element(s) that have the specified attribute with a value that ends with val:

a[href$='.jpg'], a[href$='.png'] {
  background: greenyellow;
}

:link :visited :hover & :active link pseudo-class selectors

These 4 pseudo-classes are useful to select elements such as links in various states. These 4 are most often used with links, but :active is also useful for buttons and :hover can be used on all kinds of elements:

  • :link - Targets unvisited links. It allows you to style hyperlinks that the user hasn't clicked on yet.
  • :visited - Targets links that have already been visited by the user. This pseudo-class lets you apply styles to previously clicked hyperlinks.
  • :hover - Targets elements (commonly links) when they are being hovered over by the user's pointer, such as a mouse cursor.
  • :active - Targets elements (typically links or buttons) during the moment they are being activated, like when a user clicks on them.
a:link {
  background: aliceblue;
}
a:visited {
  background: blanchedalmond;
}
a:hover {
  background: honeydew;
}
a:active {
  background: lavenderblush;
}

:focus focused input element(s)

The :focus pseudo-class targets an element when it receives focus, such as when a user clicks on an input field or navigates to it using the keyboard:

input:focus {
  border: 2px solid deepskyblue;
  background: lightcyan;
  outline: none;
  box-shadow: 0 0 8px rgba(0, 191, 255, 0.5);
}
Your name:

:checked checked input element(s)

The :checked pseudo-class targets radio buttons, checkboxes, or options in a select element that are currently selected/checked.

In the following example I make use of appearance: none to remove the default styling of the checkbox input, then use the :checked pseudo-class to style the sibling label, while also adding styling on the label when the checkbox is focused:

input[type='checkbox'] {
  /* remove default
     checkbox styles */
  all: unset;
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
}
input[type='checkbox']:checked + label {
  background: mediumseagreen;
}
input[type='checkbox']:focus + label {
  box-shadow: 0 0 0 2px yellow;
}
I am a label

:disabled disabled input element(s)

The :disabled pseudo-class matches form elements like buttons or text inputs that are disabled:

input[type="text"] {
  padding: 10px;
  border: 2px solid mediumslateblue;
  margin-right: 10px;
}

input[type="text"]:disabled {
  background: lightgray;
  border: 2px solid darkgray;
  color: darkgray;
}

:enabled enabled input element(s)

The :enabled pseudo-class matches form elements that are interactive and can receive input:

input[type="text"] {
  padding: 10px;
  border: 1px solid gray;
  margin-right: 10px;
}

input[type="text"]:enabled {
  background: lightgreen;
  border: 1px solid green;
}

:valid valid input element(s)

The :valid pseudo-class is used to target an input element that has content that matches the requirements as specified by its attributes (like pattern, type, etc.):

input[type="email"]:valid {
  border: 2px solid limegreen;
  background: honeydew;
}
Email:

:invalid invalid input element(s)

The :invalid pseudo-class is used to target input elements that have content that doesn't match the requirements:

input[type="email"]:invalid {
  border: 2px solid tomato;
  background: mistyrose;
}
Email:

:required required input element(s)

The :required pseudo-class targets input elements that have the required attribute, indicating that they must be filled out before the form can be submitted:

input:required {
  border: 2px dotted orangered;
  background: floralwhite;
  box-shadow: 0 0 10px rgba(255, 69, 0, 0.2);
}
Name (required): Optional Field:

:optional optional input element(s)

The :optional pseudo-class targets input elements that do not have the required attribute, implying that they're not mandatory to fill out:

input:optional {
  border: 2px dotted darkgray;
  background: whitesmoke;
  box-shadow: 0 0 10px rgba(105, 105, 105, 0.2);
}
Name (required): Optional Field:

:first-child first child element

The :first-child pseudo-class targets the first child element within its parent:

div {
  border: 1px dotted gray;
}

div:first-child {
  background: lightblue;
  border-color: deepskyblue;
  border-style: solid;
}
First Child
Second Child
Third Child

:last-child last child element

The :last-child pseudo-class targets the last child element within its parent:

div {
  border: 1px dotted gray;
}

div:last-child {
  background: lightblue;
  border-color: deepskyblue;
  border-style: solid;
}
First Child
Second Child
Last Child

:nth-child nth child element

The :nth-child pseudo-class targets elements based on their position within their parent, allowing for a wide variety of selections.

:nth-child also lets you select elements in patterns:

  • :nth-child(odd) or :nth-child(2n+1) selects every odd-numbered child
  • :nth-child(even) or :nth-child(2n) selects every even-numbered child

The 'n' in the formula is like a counter, letting you target elements in repeating cycles. For instance, :nth-child(3n) would target every third element.

div {
  border: 1px dotted gray;
}

div:nth-child(2) {
  background: lightcoral;
  border-color: darkred;
  border-style: solid;
}
First Child
Second Child
Last Child

:nth-last-child nth child element, counting backwards from last

The :nth-last-child pseudo-class is similar to :nth-child, but it counts from the last child backwards:

div {
  border: 1px dotted gray;
}

div:nth-last-child(2) {
  background: darkorchid;
  border-color: indigo;
  color: white;
  border-style: solid;
}
First Child
Second Child
Third Child
Last Child

:only-child only child of an element

The :only-child pseudo-class targets an element if it's the only child element of its parent:

div {
  border: 1px dotted gray;
}

div:only-child {
  background: lightsalmon;
  border-color: darksalmon;
  border-style: solid;
}
1st Child
Inner child 1
Inner child 2
2nd Child
Only child of '2nd Child'

:first-of-type first element of a type

The :first-of-type pseudo-class targets the first element of its type within its parent:

p, div {
  border: 1px dotted gray;
}

div:first-of-type {
  background: lightyellow;
  border-color: gold;
  color: darkorange;
  border-style: solid;
}

First paragraph

Second paragraph

First div
Second div

:last-of-type last element of a type

The :last-of-type pseudo-class targets the last element of its type within a parent:

p, div {
  border: 1px dotted gray;
}

p:last-of-type {
  background: lightyellow;
  border-color: gold;
  color: darkorange;
  border-style: solid;
}

First paragraph

Second paragraph

First div
Second div

:nth-of-type nth element of a type

The :nth-of-type pseudo-class matches elements based on their type and position among siblings:

p, div {
  border: 1px dotted gray;
}

p:nth-of-type(3) {
  background: lightyellow;
  border-color: gold;
  color: darkorange;
  border-style: solid;
}

First paragraph

Second paragraph

Third paragraph

First div
Second div
Third div

:nth-last-of-type nth element of type, counting backwards

The :nth-last-of-type pseudo-class matches elements based on their type and position among siblings, but counting from the end:

p, div {
  border: 1px dotted gray;
}

div:nth-last-of-type(3) {
  background: lightyellow;
  border-color: gold;
  color: darkorange;
  border-style: solid;
}

First paragraph

Second paragraph

Third paragraph

First div
Second div
Third div

:only-of-type only element of its type

The :only-of-type pseudo-class targets an element that is the only element of its type among its siblings:

p, div {
  border: 1px dotted gray;
}

:only-of-type {
  background: lightyellow;
  border-color: gold;
  color: darkorange;
  border-style: solid;
}

First paragraph

Second paragraph

First div

Paragraph

:target target element selector

The :target pseudo-class selects an element with an ID attribute matching the URL fragment (eg: https://example.com/#fragment).

:target is often used to style sections of a page that are directly linked to, typically used with in-page links:

div:target {
  border: 3px solid deepskyblue;
  background-color: lightcyan;
  transform: scale(1.05);
}
Go to Section 1 Go to Section 2
Section 1 content
Section 2 content

:not() negation pseudo-class

The :not() functional pseudo-class allows you to target elements that do not match a specified selector or condition. It's essentially an exclusion filter:

div:not(.exclude) {
  border: 2px solid royalblue;
  background: aliceblue;
}
This div is targeted
This div has the '.exclude' class
Another targeted div

:has() parent selector

The :has() functional pseudo-class allows to style an element if it contains a certain element or another selector:

div:has(p.special) {
  border: 2px solid darkkhaki;
  background-color: peachpuff;
}

Regular paragraph.

This paragraph has a the '.special' class, so its parent div is styled!

Another regular paragraph.

::before first child pseudo-element

The ::before pseudo-element is used to insert content before the content of an element. It can be used to add decorative content, icons, or other elements that don't need to be in the actual DOM:

.alert::before {
  content: '⚠️ ';
  margin-right: 0.25rem;
}
This is an alert message

::after last child pseudo-element

The ::after pseudo-element is similar to ::before and is used to insert content after the content of an element:

.info::after {
  content: '';
  display: inline-block;
  width: 0.75rem;
  height: 0.75rem;
  border-radius: 35%;
  background: darkseagreen;
  margin-left: 0.35rem;
  rotate: 45deg;
  vertical-align: middle;
}
My message

::first-letter first letter pseudo-element

The ::first-letter pseudo-element is used to style the first letter of a block-level element, allowing for design elements like drop caps:

p::first-letter {
  font-size: 2em;
  font-weight: bold;
  float: left;
  color: crimson;
}

Once upon a time, in a land far, far away, there lived a curious coder on a quest for knowledge.

::first-line first line pseudo-element

The ::first-line pseudo-element is used to style the first line of a block-level element. This allows for typographic effects that can adapt dynamically based on the size of the containing element and the font size:

p::first-line {
  font-weight: bold;
  color: darkslategray;
  text-transform: uppercase;
}

It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness...

::placeholder text input placeholder

The ::placeholder pseudo-element is used to style the placeholder text of form fields like <input> and <textarea>:

input::placeholder {
  font-style: italic;
  color: thistle;
  opacity: 0.7;
}

::selection style highlighted box

The ::placeholder pseudo-element is used to style the portion of an element that has been highlighted or selected by the user. For instance, when a user clicks and drags to select text, the ::selection pseudo-element can be used to modify the background color, text color, and other styles of that selection:

::selection {
  background-color: gold;
  color: darkblue;
}

Click and drag to select this text to see the custom selection styling in action.

::marker list marker pseudo-element

The ::marker pseudo-element is used to style marker boxes in list items, which typically contain bullets (for unordered lists) or numbers/letters (for ordered lists).

Before the introduction of the ::marker pseudo-element, customizing these markers often required workarounds, but this pseudo-element gives us a bit more control:

li::marker {
  color: LightSeaGreen;
  font-size: 1.5em;
  font-weight: bold;
}
  • Apples 🍎
  • Bananas 🍌
  • Cherries 🍒

More pseudo-classes

Here's some additional pseudo-classes that are available in CSS:

  • :root: Targets the highest-level parent element in a document, typically the <html> element in HTML documents. Useful to define CSS variables that will be available to all elements within the page.
  • :is(): Matches elements that can be one of several selectors, making long selector lists shorter and easier to read. For example, :is(h1, h2, h3) would match any of those three heading elements.
  • :where(): Similar to :is(), but allows for selecting elements based on conditions without affecting the specificity of the selector.
  • :default: Matches UI elements (like radio buttons or checkboxes) that are set to their default selection state.
  • :empty: Selects elements that have no children (including text nodes).
  • :fullscreen: Targets elements that are currently displayed in fullscreen mode.
  • :in-range: Matches form elements with a value that is within the specified range (using attributes like min and max).
  • :out-of-range: Matches form elements with a value that is outside the specified range.
  • :indeterminate: Targets form elements whose state is uncertain, such as a checkbox that's neither checked nor unchecked (often seen in tree-view structures).
  • :read-only: Matches form elements that are not editable by the user, due to the readonly attribute.
  • :read-write: Targets form elements that are editable by the user, implying they are not readonly.
  • :lang(): Matches elements based on their language attribute. E.g., :lang(en) selects elements defined in English.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK