CSS selectors identify specific HTML elements as targets for CSS styles. This topic covers how CSS selectors target HTML elements. Selectors use a wide range of over 50 selection methods offered by the CSS language, including elements, classes, IDs, pseudo-elements and pseudo-classes, and patterns.
Basic CSS selectors
|*||Universal selector (all elements)|
|div||Tag selector (all <div> elements)|
|.blue||Class selector (all elements with class blue)|
|.blue.red||All elements with class blue and red (a type of Compound selector)|
|#headerline||ID selector (the element with "id" attribute set to headline)|
|:pseudo-class||All elements with pseudo-class|
|::pseudo-element||The element that matches pseudo-element|
|:lang(en)||Element that matches :lang declaration, for example <span lang="en">|
|div > p||child selector|
CSS Attribute Selectors
Attribute selectors can be used with various types of operators that change the selection criteria accordingly. They select an element using the presence of a given attribute or attribute value.
|Selector(1)||Matched element||Selects elements...||CSS Version|
|[attr]||<div attr>||With attribute attr||2|
|[attr='val']||<div attr="val">||Where attribute attr has value val||2|
|[attr~='val']||<div attr="val val2 val3">||Where val appears in the whitespace separated list of attr||2|
|[attr^='val']||<div attr="val1 val2">||Where attr's value begins with val||3|
|[attr$='val']||<div attr="sth aval">||Where the attr's value ends with val||3|
|[attr*='val']||<div attr="somevalhere">||Where attr contains val anywhere||3|
||<div attr="val-sth etc">||Where attr's value is exactly val, or starts with val and immediately followed by - (U+002D)||2|
|[attr='val' i]||<div attr="val">||Where attr has value Val, ignoring Val's letter casing.||4(2)|
Selects elements with the given attribute.
Selects elements with the given attribute and value.
Selects elements with the given attribute and value where the given attribute contains the given value anywhere (as a substring).
Selects elements with the given attribute and value where the given value appears in a whitespace-separated list.
Selects elements with the given attribute and value where the given attribute begins with the value.
Selects elements with the given attribute and value where the given attribute ends with the given value.
Selects elements with a given attribute and value where the attribute's value is exactly the given value or is exactly the given value followed by - (U+002D)
Selects elements with a given attribute and value where the attribute's value can be represented as Value, VALUE, vAlUe or any other case-insensitive possibility
Specificity of attribute selectors
Same as class selector and pseudoclass.
*[type=checkbox] // 0-1-0
|div span||Descendant selector (all <span>s that are descendants of a <div>)|
|div>span||Child selector (all <span>s that are a direct child of a <div>)|
|a ~ span||General Sibling selector (all <span>s that are siblings after an <a>)|
|a + span||Adjacent Sibling selector (all <span>s that are immediately after an <a>)|
Descendant Combinator: selector selector
A descendant combinator, represented by at least one space character (), selects elements that are a descendant of the defined element. This combinator selects all descendants of the element (from child elements on down).
In the above example, the first two <p> elements are selected since they are both descendants of the <div>.
Child Combinator: selector > selector
The child (>) combinator is used to select elements that are children, or direct descendants, of the specified element.
The above CSS selects only the first <p> element, as it is the only paragraph directly descended from a <div>.
The second <p> element is not selected because it is not a direct child of the <div>.
Adjacent Sibling Combinator: selector + selector
The adjacent sibling (+) combinator selects a sibling element that immediately follows a specified element.
The above example selects only those <p> elements that are directly preceded by another <p> element.
General Sibling Combinator: selector ~ selector
The general sibling (~) combinator selects all siblings that follow the specified element.
The above example selects all <p> elements that are preceded by another <p> element, whether or not they are immediately adjacent.
Pseudo-classes are keywords that allow selection based on information that lies outside of the document tree or that cannot be expressed by other selectors or combinators. This information can be associated with a certain state (state and dynamic pseudo-classes), to locations (structural and target pseudo-classes), to negations of the former (negation pseudo-class), or to languages (lang pseudo-class). Examples include whether or not a link has been followed (: visited), the mouse is over an element (: hover), a checkbox is checked (: checked), etc.
List of pseudo-classes Name and Descriptions:
- : active - Applies to any element being activated (i.e. clicked) by the user.
- : any - Allows you to build sets of related selectors by creating groups that the included items will match. This is an alternative to repeating an entire selector.
- : target - Selects the current active #news element (clicked on a URL containing that anchor name)
- : checked - Applies to radio, checkbox, or option elements that are checked or toggled into an "on" state.
- : default - Represents any user interface element that is the default among a group of similar elements.
- : disabled - Applies to any UI element which is in a disabled state.
- : empty - Applies to any element which has no children.
- : enabled - Applies to any UI element which is in an enabled state.
- : first - Used in conjunction with the @page rule, this selects the first page in a printed document.
- :first-child - Represents any element that is the first child element of its parent.
- :first-of-type - Applies when an element is the first of the selected element type inside its parent. This may or may not be the first child.
- : focus - Applies to any element which has the user's focus. This can be given by the user's keyboard, mouse events, or other forms of input.
- :focus-within - Can be used to highlight a whole section when one element inside it is focused. It matches any element that the: focus pseudo-class matches or that has a descendant focused.
- :full-screen - Applies to any element displayed in full-screen mode. It selects the whole stack of elements and not just the top-level element.
- : hover - Applies to any element being hovered by the user's pointing device, but not activated.
- : indeterminate - Applies radio or checkbox UI elements that are neither checked nor unchecked, but are in an indeterminate state. This can be due to an element's attribute or DOM manipulation.
- :in-range - The:in-range CSS pseudo-class matches when an element has its value attribute inside the specified range limitations for this element. It allows the page to give feedback that the value currently defined using the element is inside the range limits.
- :invalid - Applies to <input> elements whose values are invalid according to the type specified in the type= attribute.
- : lang - Applies to any element whose wrapping <body> element has a properly designated lang= attribute. For the pseudo-class to be valid, it must contain a valid two or three-letter language code.
- :last-child - Represents any element that is the last child element of its parent.
- :last-of-type - Applies when an element is the last of the selected element type inside its parent. This may or may not be the last child. : left Used in conjunction with the @page rule, this selects all the left pages in a printed document.
- : link - Applies to any links which haven't been visited by the user.
- :not() - Applies to all elements which do not match the value passed to (:not(p) or :not(.class-name) for example. It must have a value to be valid and it can only contain one selector. However, you can chain multiple: not selectors together.
- :nth-child - Applies when an element is the n-th element of its parent, where n can be an integer, a mathematical expression (e.g n+3) or the keywords odd or even.
- :nth-of-type - Applies when an element is the n-th element of its parent of the same element type, where n can be an integer, a mathematical expression (e.g n+3), or the keywords odd or even.
- :only-child - The:only-child CSS pseudo-class represents any element that is the only child of its parent. This is the same as :first-child:last-child or :nth-child(1):nth-last-child(1), but with a lower specificity.
- : optional - The: optional CSS pseudo-class represents any element that does not have the required attribute set on it. This allows forms to easily indicate optional fields and to style them accordingly.
- :out-of-range - The:out-of-range CSS pseudo-class matches when an element has its value attribute outside the specified range limitations for this element. It allows the page to give feedback that the value currently defined using the element is outside the range limits. A value can be outside of a range if it is either smaller or larger than maximum and minimum set values.
- :placeholder-shown - Experimental. Applies to any form element currently displaying placeholder text.
- : read-only - Applies to any element which is not editable by the user.
- : read-write - Applies to any element that is editable by a user, such as <input> elements.
- : right - Used in conjunction with the @page rule, this selects all the right pages in a printed document.
- : root - matches the root element of a tree representing the document.
- : scope - CSS pseudo-class matches the elements that are a reference point for selectors to match against.
- : target - Selects the current active #news element (clicked on a URL containing that anchor name)
- : visited - Applies to any links which have been visited by the user.
Child Pseudo Class
"The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n" - MDN :nth-child
CSS Class Name Selectors
The class name selector select all elements with the targeted class name. For example, the class name .warning would select the following <div> element:
You can also combine class names to target elements more specifically. Let's build on the example above to showcase a more complicated class selection.
In this example, all elements with the .warning class will have a blue text color, elements with the .important class with have an orange text color, and all elements that have both the .important and .warning class name will have a red text color.
Notice that within the CSS, the .warning.important declaration did not have any spaces between the two class names. This means it will only find elements that contain both class names warning and important in their class attribute. Those class names could be in any order on the element. If space was included between the two classes in the CSS declaration, it would only select elements that have parent elements with a .warning class names and child elements with .important class names.
Select element using its ID without the high specificity of the ID selector
This trick helps you select an element using the ID as a value for an attribute selector to avoid the high specificity of the ID selector.
The :last-of-type selector
The:last-of-type selects the element that is the last child, of a particular type, of its parent. In the example below, the css selects the last paragraph and the last heading h1.
CSS3 :in-range selector example
The:in-range CSS pseudo-class matches when an element has its value attribute inside the specified range limitations for this element. It allows the page to give feedback that the value currently defined using the element is inside the range limits.
A. The :not pseudo-class example & B. :focuswithin CSS pseudo-class
A. The syntax is presented above.
The following selector matches all <input> elements in an HTML document that are not disabled and don't have the class .example:
The :not() pseudo-class will also support comma-separated selectors in Selectors Level 4:
See background syntax here.
B. The :focus-within CSS pseudo-class
Global boolean with a checkbox:checked and ~ (general sibling combinator)
Add boolean as a checkbox
To the very beginning of your document, add as many booleans as you want with a unique id and the hidden attribute set:
Change the boolean's value
You can toggle the boolean by adding a label with the for attribute set:
Accessing boolean value with CSS
The normal selector (like .color-red) specifies the default properties. They can be overridden by following true / false selectors:
Note that <checkbox>, [sibling ...] and <target> should be replaced by the proper selectors. [sibling ...] can be a specific selector, (often if you're lazy) simply * or nothing if the target is already a sibling of the checkbox.
Examples for the above HTML structure would be:
CSS ID selectors
ID selectors select DOM elements with the targeted ID. To select an element by a specific ID in CSS, the # prefix is used.
For example, the following HTML div element…
…can be selected by #exampleID in CSS as shown below:
How to style a Range input
Effect and Pseudo Selector
- Thumb - input[type=range]::-webkit-slider-thumb, input[type=range]::-moz-range-thumb, input[type=range]::-ms-thumb
- Track - input[type=range]::-webkit-slider-runnable-track, input[type=range]::-moz-range-track, input[type=range]::-ms-track
- OnFocus - input[type=range]:focus
- Lower part of the track - input[type=range]::-moz-range-progress, input[type=range]::-ms-fill-lower (not possible in WebKit browsers currently - JS needed)
The :only-child pseudo-class selector example
The :only-child CSS pseudo-class represents any element which is the only child of its parent.
The above example selects the <p> element that is the unique child from its parent, in this case, a <div>
ATutorialHub Related Guide
panduranga gupta2021-07-05 07:03:13
good website for learning and help me a lot
The awsome website i am looking like for a long time, good work atutorialhub team keep doing
Learning a lot from the courses present on atutorialhub. The courses are very well explained. Great experience
It is very helpful to students and easy to learn the concepts
Great job Tutorials are easy to understand Please make use of it
Zain Khan2021-09-18 15:07:23
Great content and customized courses.
Rudrakshi Bhatt2021-09-09 15:08:10
Well structured coursed and explained really well!
Pavana Somashekar2021-09-11 15:09:08
Good platform for beginners and learn a lot on this website