CSS Selectors, Pseudo Classes and Elements

shohanur rahmanshohanur rahman
10 min read
SelectorBehavior
.class1.class2Elements with both classes
.c1 .c2c2 is descendent of c1
element.classAll elements with that class
div pAll p that are inside that div (including nested)
div > pOnly the p that are immediate/direct child of that div. Nested p will not e included. Means the p whose direct parent is the div.
div + pthe first p after that div (has closed, completed). e.g: <div></div><p></p>
div ~ pall p after that div (has closed, completed) e.g: <div></div><p></p><p></p>..<p></p>

Attribute Selectors

SelectorExampleBehavior
Presence: [attribute][lang]Selects all elements with a lang attribute regardless of the value
Exact match: [attribute =value][lang="it"]Selects all elements with lang="it"
Whitespace Separated: [attribute ~=value][tags ~= "red"]Selects elements where the specified attribute's value is a list of whitespace-separated words, and one of those words is exactly flower. e.g:<div tags="red"></div> and <div tags="red green"></div> will be selected but <div tags="red-green blue"></div> will not be selected.
Hyphen Separated: [attribute\=value[lang
Prefix Match: [attribute ^=value][href ^= "https"]Selects all elements with a href attribute value that begins with "https"
Suffix Match: [attribute $=value][href $= ".pdf"]Selects all elements with a href attribute value ends with ".pdf"
Substring Match: [attribute *=value][tags *= "red"]Selects all elements with a href attribute value containing the substring "test" e.g: <div tags="red">, <div tags="red green">, <div tags="red-green blue"> will all be selected

Combining Attribute Selectors

You can combine attribute selectors for more specific targeting:

<input type="text" data-validation="required email">
<input type="text" data-validation="required">
<input type="email" data-validation="email">
input[type="text"][data-validation*="required"] {
  border: 1px solid red; /* Selects the first two inputs */
}

Pseudo Classes:
A pseudo-class is used to define a special state of an element. Pseudo-classes are keywords added to selector. They allow you to apply styles when something happens, like when a user hovers over a link, or when an element is the first or last of its kind. They let you style an element based on its state or position in the document tree, rather than its content or attributes.

SelectorExampleBehavior
:first-childp:first-childSelects the p that is the first child of its parent. But it’s not like select the first <p> element inside parent rather only if the first child is <p>. e.g: <div><p></p><p></p></div> Here the first p will be selected. But <div><li></li><p></p></div>nothing will be selected here. Because the first child is <li>.
:first-of-typep:first-of-typeSelects the first element of its type among a group of sibling elements.
:nth-child()p:nth-child(2)Selects any <p> element that is the second child of its parent.
:nth-last-child()p:nth-last-child(2)Selects any <p> element that is the second child of its parent, counting from the end.
:nth-of-type()p:nth-of-type(2)Selects any <p> element that is the second <p> element of its parent.
:nth-last-of-type()p:nth-last-of-type(2)Selects any <p> element that is the second <p> element of its parent, counting from the end.
:only-childp:only-childSelects any <p> element that is the only child of its parent. The parent has no other children.
:only-of-typep:only-of-typeSelects any <p> element that is the only <p> element of its parent
:last-childli:last-childSelects any <li> element that is the last child of its parent
:last-of-typep:last-of-typeSelects any <p> elemet
:activea:activeSelects the active link
:any-linka:anylinkSelects any <a> or <area> element with an href attribute
:linka:linkSelects any unvisited link
:visiteda:visitedSelects all visited links
:auto-fillinput:autofillSelects any <input> element with its value autofilled by the browser
:checkedinput:checked, option:checkedMatches any <input> or <option> element that is checked
:defaultinput:default, option:defaultSelects form elements that are default in a group of related elements
:disabledinput:disabled, option:disabledSelects any element that is disabled. Most used for form elements
:enabledinput:enabledSelects any element that is enabled. Most used for form elements
:in-rangeinput:in-rangeSelect any <input> element with a value within the specified range limit
:out-of-rangeinput:out-of-rangeSelects any <input> element with a value outside the specified range limit
:validinput:validSelects all input elements with a valid value
:invalidinput:invalidSelects invalid form elements
:user-invalid:user-invalidSelects any form element with an invalid value (after the user have interacted with it)
:user-valid:user-validSelects any form element with a valid value (after the user have interacted with it)
:requiredinput:requiredSelects input elements with the "required" attribute specified
:optionalinput:optional, textarea:optionalSelects any <input>, <select>, or <textarea> elements without a "required" attribute
:placeholder-showninput:placeholder-shown, textarea:placeholder-shownSelects any <input> or <textarea> element that is currently displaying placeholder text
:read-onlyinput:read-onlySelects input elements with the "readonly" attribute specified
:read-writeinput:read-writeSelects editable input elements
:emptydiv:emptySelects any element that has no children, completely empty, contains nothin on the DOM.
:root:rootSelects the document's root element
:lang()p:lang(it)Selects any <p> element with a lang attribute equal to "it" (Italian)
:right@page :rightRepresents all right-hand pages of a printed document (used with the @page rule)
:left@page :leftRepresents all left-hand pages of a printed document (used with the @page rule)
:scope:scopeSelects elements that are a reference point, or scope, for selectors to match against
:state():state()Selects custom elements that have the specified custom state
:target:targetSelects the target element. e.g: <div id=”abc”></div> is a target. You can go to the target by clicking <button href=”#abc”></button>
:target-within:target-withinMatches elements which are the targets, but also elements which have a descendant which is the target of the document URL.
:not():not(p)Selects any element that is not a <p> element
:modal:modalSelects the element that is in a modal state
:hovera:hoverSelects element on mouse over
:focusinput:focus, select:focusSelects the element that gets focus. Most used for form elements
:focus-visiblebutton:focus-visibleSelects the element that gets focus (used to apply focus styles only when the keyboard is used to focus something, not the mouse)
:focus-withinform:focus-withinMatches an element if the element or any of its descendants gets focus
:fullscreen:fullscreenSelects any element that is currently in full-screen mode. e.g: element.requestFullscreen() function invoked in JS to turn that element take fullscreen. That time that style will take effect.
:playing:playingRepresents a playable element that is playing.
:paused:pausedRepresents a playable element that is paused.
:seeking:seekingA resource is considered to be seeking if the user has requested playback of a specific position in the media resource, but the media element has not yet reached that position. Seeking is different from :buffering in that the media element is not currently loading data, but is instead skipping to a new position in the media resource.
:buffering:bufferingRepresents a playable element that is playing but is temporarily stalled because it is downloading the media resource. That element cannot continue playing because it is trying to load media data but does not yet have enough data to begin or continue playback.
:stalled:stalledA resource is considered to be stalled if the user has requested playback of a specific position in the media resource, but it has failed to receive any data for some amount of time because it cannot download the media resource. This is different from :buffering where the media element is unexpectedly not loading data when stalled (e.g., due to a network error). Means, stall first then buffering may happen or not happen. But stall first then depends if the data has loaded or not. Like with the :buffering pseudo-class, the element is still considered to be "playing" when it is "stalled". If :stalled matches an element, :playing will also match that element.
:muted:mutedRepresents a sound-producing element that is muted.
:volume-locked:volume-lockedRepresents an element that is capable of making sound, such as <audio> or <video>, but the audio volume of the media element is currently "locked" by the user.
:is(), where(), has()Check below.

Pseudo Elements:
A CSS pseudo-element is used to style specific parts of an element. They are not actual HTML elements, but they allow you to style parts of an element as if they were separate elements. They act as if you had added a whole new HTML element into the markup, rather than applying a class to existing elements.

SelectorExampleBehavior
::afterp::afterInserts something after the content of the specified element
::beforep::beforeInserts something before the content of the specified element
::placeholderinput::placeholderStyles the placeholder text of <input> element
::marker::markerSelects the markers of list items
::file-selector-button::file-selector-buttonSelects any button of type <input type="file">
::selection::selectionStyles the user-selected text
::backdropdialog::backdropStyles the viewbox behind a dialog box or popover element
::spelling-error::spelling-errorStyles a text that the browser has flagged as incorrectly spelled
::grammar-error::grammar-errorStyles a text that the browser has flagged as grammatically incorrect
::-webkit-scrollbar::-webkit-scrollbar { width: 10px; }Selects the scrollbar of an element. This is a non-standard pseudo-element, and only works in WebKit-based browsers (Chrome, Safari).
::-webkit-scrollbar-track::-webkit-scrollbar-track { background: #f1f1f1; }Selects the track (the background) of the scrollbar.
::-webkit-scrollbar-thumb::-webkit-scrollbar-thumb { background: #888; border-radius: 5px; }Selects the "thumb" (the draggable part) of the scrollbar.
::scroll-button()::scroll-button(<scroll-button-direction>)Represents a button for controlling the scrolling of a scroll container. They are generated on scroll containers when their content value is not none. The direction of the scrolling is determined by the parameter value.
::scroll-marker::scroll-markerCan be generated inside any element and represents its scroll marker. All elements can have a ::scroll-marker pseudo-element, , which is placed into the ::scroll-marker-group of the nearest scroll container ancestor. A scroll marker behaves like an anchor (<a> element) whose scroll target is the marker's originating element — and scrolls the scroll container to that element when activated.
::scroll-marker-group::scroll-marker-groupThis is a container that automatically contains any ::scroll-marker pseudo-elements generated on itself or its descendants. This allows them to be positioned and laid out as a group, and is typically used when creating a CSS carousel to provide a scroll position indicator. The individual scroll markers can be used to navigate to their associated content items.

:is(), :where(), :has() :

0
Subscribe to my newsletter

Read articles from shohanur rahman directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

shohanur rahman
shohanur rahman