CSS Selectors: A Complete Guide
Welcome! This comprehensive guide explains what CSS selectors are, why they matter, the different types you can use, and how to apply them in real-world projects.
- Ancestors, Descendants, Parents, and Children in HTML
- What Are CSS Selectors?
- * — The Universal Selector
- #A — The ID Selector
- .A — The Class Selector
- A B — The Descendant Combinator
- AB — A Compound Selector for the Same Element
- A > B — The Child Combinator
- A ~ B — The General Sibling Combinator
- A + B — The Adjacent Sibling Combinator
- A — The Type Selector
- A[title] is a selector by attribute
- A[attribute="value"] — The Exact Attribute Value Selector
- A[attribute*="value"] — The Attribute Substring Selector
- A[attribute^="value"] — The Attribute Prefix Selector
- A[attribute$="value"] — The Attribute Suffix Selector
- A[attribute~="value"] — The Space-Separated Attribute Value Selector
- A:visited and A:link — Visited and Unvisited Link Pseudo-classes
- A:checked — The Checked Radio Button or Checkbox Selector
- ::before and ::after — Pseudo-elements
- A:hover — The Hover Pseudo-class
- A:not(selector) — The Negation Pseudo-class
- A::pseudo-element — A Pseudo-element Selector
- A:first-child and A:last-child — The First and Last Child Selectors
- A:only-child — The Only-child Selector
- A:nth-child(n) — Select an Element by Position
- A:nth-last-child(n) — Select an Element by Position from the End
- A:nth-of-type(n) — Select by Position Among Siblings of the Same Type
- A:nth-last-of-type(n) — Select by Position from the End Among Siblings of the Same Type
- A:only-of-type — Select the Only Sibling of Its Type
- A:first-of-type — Select the First Element of a Given Type
- A:has() — Select a Parent or Ancestor Based on Its Contents
- :has() — Combining Selectors
- :has() — Using Pseudo-classes
- :has() — Multiple Levels of Nesting
- :has() — Practical Examples
- Grouping Selectors
- How Browsers Read CSS Selectors
- Inheritance in CSS
- CSS Selector Specificity: The Cascade, Weight, and Priority
- Resetting Specificity
- How to Visualize the Cascade on a Web Page
- What Happens When External and Internal Stylesheets Conflict?
- Practical Examples
- Add Right Spacing to Every List Item Except the Last (Example 1)
- Add Right Spacing to Every List Item Except the Last (Example 2)
- Styling Form Placeholders
- Select the First Child Element, Regardless of Type
- Select All Children of a Block When They Have No Separate Classes
- How to Style Links Without a Class
- Why Is This Useful?
- How Does It Work?
- Clarification: What Does Not Count?
- CSS Pseudo-classes for Element States: :hover, :focus, and :active
- Key States of Interactive Elements
- :hover
- :focus
- :active
- How Element States Affect Accessibility
Before we dive in, let’s clarify two key concepts in the HTML structure: ancestors and child elements.
Ancestors, Descendants, Parents, and Children in HTML
Let's take the simplest HTML markup as an example
<html>
<head>
<title>Simple document</title>
</head>
<body>
<h1>Document title</h1>
<p>Paragraph with <strong>important </strong>text.</p>
</body>
</html>
- Ancestor. An element that contains another element is its ancestor. Here,
<html>is an ancestor of every element on the page, while<body>is an ancestor of the elements inside it:<h1>,<p>, and<strong>. - Descendant. An element nested inside another element is its descendant. Here,
<body>is a descendant of<html>, and<p>is a descendant of both<body>and<html>. - Parent element. A parent is the immediate ancestor of another element.
<html>is the parent of<head>and<body>, while<p>is the parent of<strong>. - Child element. A child is the immediate descendant of another element. Here,
<h1>and<p>are children of<body>.<strong>is not a child of<body>; it is nested directly inside<p>, so it is a child of that paragraph. - Sibling elements. Elements that share the same parent are siblings. For example,
<head>and<body>are siblings, as are<h1>and<p>.
What Are CSS Selectors?
CSS selectors are used to select (find) HTML elements on site pages that need to be styled. Allows you to select both a whole group of DOM tree elements and smaller ones based on specific attributes.
Selectors can be classified into 5 main categories:
- Simple selectors, which allow you to select elements by their name, ID or class.
- Combinator selectors select elements based on their relationships to each other.
- Pseudo-class selectors select elements based on their current state or condition.
- Pseudo-element selectors used to style specific parts of elements.
- Attribute selectors that allow you to select elements based on the presence of attributes or their values.
I'll start with the simplest ones.
* — The Universal Selector
/* Select all tags */
* {
margin: 0px;
padding: 0px;
border: 0px;
}
The universal selector selects all elements on the page. This means that the above code will select each tag on the page and apply the 3 specified CSS styling rules to it.
Usually used to reset (clear) styles at the beginning of the project layout. It is not recommended to use further in the code, because it loads the client's browser.
Using the universal selector, you can also select children of elements.
/* Select all child elements of a tag with id="wrapper" */
#wrapper * {
padding: 0px 15px 0px 15px;
}
/* Select only direct descendants of a tag with id="wrapper" */
#wrapper > * {
padding: 0px 15px 0px 15px;
}
#A — The ID Selector
#wrapper {
padding: 0px;
}
The hash symbol (#) targets an element with a specific, unique ID:
<div id="wrapper">
...
</div>
Remember that the identifier
idmust be unique and used only once within a page.
Selecting elements by ID is considered bad practice. The use of such a selector is not justified due to browser style priorities. In the future, it will be quite difficult to override it to change the styles of this element. The best option is a class selector.
.A — The Class Selector
.wrapper {
padding: 0px;
}
Selects HTML elements by class name.
The number of elements with the same class within one page can be any number.
<nav class="nav">
<a class="nav__link nav__link--active">Main</a>
<a class="nav__link" href="#">Second</a>
<a class="nav__link" href="#">Third</a>
<a class="nav__link" href="#">Fourth</a>
<a class="nav__link" href="#">End</a>
</nav>
A B — The Descendant Combinator
Used to select elements that satisfy a certain context. For example, there is a code
<div class="content">
<p>text 1</p>
<p>text 2</p>
<div class="content__body content-body">
<p>text 3</p>
<p>text 4</p>
<div class="content-body__text">
<p>text 5</p>
</div>
</div>
</div>
It requires <p> change color:
.content p {
color: red;
}
AB — A Compound Selector for the Same Element
Sometimes you can see the following code
h2.slider__title {
color: red;
}
This code will be applied to an HTML element
<h2 class="slider__title">Slider Title</h2>
The selector will select an element in which the tag <h2> and the class .slider__title.
are present at the same time. This selector does not make any sense, because the same result can be obtained as follows:
.slider__title {
color: red;
}
The thing is that in layout, the title tag can change from <h2> to <h3>, for example. In this case, the h2.slider__title{} construction will no longer work.
A > B — The Child Combinator
If you want to change the color only for the direct descendants of the main container (this is the text "text 1" and "text 2"):
.content > p {
color: red;
}
A ~ B — The General Sibling Combinator
If you want to select only "right neighbors", that is, at the same level of nesting with the container <div class="content"></div>. For example:
<p>text 8</p>
<p>text 9</p>
<div class="content">
<p>text 1</p>
<p>text 2</p>
<div class="content__body content-body">
<p>text 3</p>
<p>text 4</p>
<div class="content-body__text">
<p>text 5</p>
</div>
</div>
</div>
<p>text 6</p>
<p>text 7</p>
The following code will color the following lines: "text 6" and "text 7":
.content ~ p {
color: red;
}
A + B — The Adjacent Sibling Combinator
To select the first adjacent element (text "text 6"):
.content + p {
color: red;
}
A — The Type Selector
You can also refer to an element by its type (or tag).
/* Select all */
div {
padding: 15px;
}
/* Select all */
a {
color: red;
}
A[title] is a selector by attribute
Let there be a block of links.
<div class="list">
<a class="list__item" href="#" title="Link 1 Title">Link 1</a>
<a class="list__item" href="#">Link 2</a>
<a class="list__item" href="#">Link 3</a>
<a class="list__item" href="#" title="Link 4 Title">Link 4</a>
</div>
Need to change the text color to those with the title attribute. The following code will select the first and last tags <a>:
/* OPTION 1 */
a[title] {
color: red;
}
/* OPTION 2 */
.list__item[title] {
color: red;
}
A[attribute="value"] — The Exact Attribute Value Selector
<div class="list">
<a href="https://site1.com">Link 1</a>
<a href="https://site2.com">Link 2</a>
<a href="https://site3.com">Link 3</a>
<a href="https://site4.com">Link 4</a>
</div>
Let the link text whose value href is equal to "https://site1.com".
a[href="https://site1.com"] {
color: red;
}
A[attribute*="value"] — The Attribute Substring Selector
Let there be a group of links:
<div class="list">
<a href="https://site-1.com">Link 1</a>
<a href="https://site2.com">Link 2</a>
<a href="https://site3.com">Link 3</a>
<a href="https://site-4.com">Link 4</a>
</div>
It is necessary to select links whose values href contain "site-".
a[href*="site-"] {
color: red;
}
A[attribute^="value"] — The Attribute Prefix Selector
Let the above example select all elements <a> whose values href begin with "https://site-". As a result of the operation of the code below, links will be selected "Link 1" and "Link 4".
a[href^="https://site-"] {
color: red;
}
A[attribute$="value"] — The Attribute Suffix Selector
The task is to select from the block of links all those in which the value href ends with ".org".
<div class="list">
<a href="https://site.com">Link 1</a>
<a href="https://site.net">Link 2</a>
<a href="https://site.info">Link 3</a>
<a href="https://site.org">Link 4</a>
<a href="https://site2.org">Link 5</a>
</div>
The code below will select the last two links.
a[href$=".org"] {
color: red;
}
A[attribute~="value"] — The Space-Separated Attribute Value Selector
<div class="list">
<a href="https://site.com" data-info="Custom Data 1">Link 1</a>
<a href="https://site.net" data-info="Custom Data 2">Link 2</a>
<a href="https://site.info" data-info="My Data 3">Link 3</a>
<a href="https://site.org" data-info="My Data 4">Link 4</a>
<a href="https://site2.org" data-info="My Data 5">Link 5</a>
</div>
To select all elements whose attribute value data-info contains the specified characters:
/* Selects the first 2 references */
a[data-info~="Custom"] {
color: red;
}
/* Select all links */
a[data-info~="Data"] {
color: red;
}
A:visited and A:link — Visited and Unvisited Link Pseudo-classes
State pseudo-class :link is used to style links that have not yet been clicked by the user.
The :visited state is responsible for links that have been clicked or visited by the user.
a:link {
color: red;
}
a:visted {
color: blue;
}
A:checked — The Checked Radio Button or Checkbox Selector
input[type=radio]:checked {
color: red;
}
::before and ::after — Pseudo-elements
.about {
position: relative;
dispay: block;
width: 100px;
height: 100px;
}
.about::before {
content: "";
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background-color: red;
}
.about::after {
content: "";
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background-color: blue;
}
A:hover — The Hover Pseudo-class
div:hover {
background-color: blue;
}
a:hover {
text-decoration: underline;
}
A:not(selector) — The Negation Pseudo-class
<div class="list">
<a href="#">Link 1</a>
<p>Paragraph Text</p>
<span>Span text</span>
</div>
Let for example you want to select all elements in the container <div>, excluding the tag <a>.
.list:not(a) {
color: red;
}
Another example is to select all HTML elements on the page except the tag <p>:
*:not(p) {
color: red;
}
A::pseudo-element — A Pseudo-element Selector
<p>Line 1<br>Line 2</p>
A few examples.
/* Select only "Line 1" */
p::first-line {
color: red;
}
/* Select the first character of the tag: "L" */
p::first-letter {
color: red;
}
A:first-child and A:last-child — The First and Last Child Selectors
Let there be a list:
<ul>
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
<li>Element 4</li>
<li>Element 5</li>
<li>Element 6</li>
</ul>
The code below will select the first and last elements, that is <li>:
/* Select the first element of the list */
ul li:first-child {
color: red;
}
/* Select the last element of the list */
ul li:last-child {
color: blue;
}
A:only-child — The Only-child Selector
Allows you to select only the element that is the sole inheritor of its parent.
div p:only-child {
color: red;
}
In the example below, the paragraph <p>, which is the only inheritor of the element <div>, will be colored red (the text "Text 1").
<div><p>Text 1</p></div>
<div>
<p>Text 2</p>
<p>Text 3</p>
</div>
Selecting an element regardless of its type.
A:nth-child(n) — Select an Element by Position
To select from the previous example the 3rd element of the list (i.e. <li>Element 3</li>):
ul li:nth-child(3) {
color: red;
}
The selector accepts a number as a parameter. The countdown starts from 1. It can also be used to select several elements at once. For example, you need to select every third item in the list. For this, the previous example will look like:
ul li:nth-child(3n) {
color: red;
}
You can also use the operators "+" and "-".

A:nth-last-child(n) — Select an Element by Position from the End
To select the 4th element of the list from the end of the list:
ul li:nth-last-child(4) {
color: red;
}
A:nth-of-type(n) — Select by Position Among Siblings of the Same Type
Selector has the same meaning as the regular :first-child, :last-child and so on, but elements with tags other than the one to which the filter is applied are ignored when counting.
There are times when instead of selecting a child element, you need to select according to the element type.
For example, there are 5 lists on a page <ul>.
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
Only the third needs to be styled. And it does not have a unique ID (id) and a separate class. In this example, only the 3rd list will have a frame.
ul:nth-of-type(3) {
border: 1px solid red;
}
A:nth-last-of-type(n) — Select by Position from the End Among Siblings of the Same Type
The code below will frame the last list.
ul:nth-last-of-type(1) {
border: 1px solid red;
}
A:only-of-type — Select the Only Sibling of Its Type
<ul>
<li>One</li>
</ul>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
The following code will only select <li> in the first <ul>:
ul > li:only-of-type {
color: red;
}
A:first-of-type — Select the First Element of a Given Type
<div>
<p>Text</p>
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
</ul>
<ul>
<li>List Item 3</li>
<li>List Item 4</li>
</ul>
</div>
Let the tag <li> be styled with the content "List Item 2". There are several options here.
/**
* METHOD 1
*
* Find the first list, then its direct descendant. Next, select the second element.
*/
ul:first-of-type > li:nth-child(2) {
color: red;
}
/**
* METHOD 2
*
* Find list <ul> follows immediately after the (adjacent) <p> tag, then its last child.
*/
p + ul li:last-child {
color: red;
}
/**
* METHOD 3
*
* Find the first list, then the first list element from the end.*/
ul:first-of-type li:nth-last-child(1) {
color: red;
}
A:has() — Select a Parent or Ancestor Based on Its Contents
Allows you to stylize a parent or ancestor element. It can then be expanded to select one or more neighbors or children. Thanks to it, it is possible to style almost any combination of elements as individual elements or ranges.
:has() — Combining Selectors
The :has() selector can be combined with other selectors for more complex selections. For example, you can select all items <div> that contain images with certain classes:
div:has(img.my-class) {
border: 2px solid blue;
}
:has() — Using Pseudo-classes
Pseudo-classes can be used inside :has() for more accurate filtering. For example, to select all elements with the tag <a>, but only those containing images:
div:has(a:has(img)) {
background-color: red;
}
:has() — Multiple Levels of Nesting
:has() supports multiple nesting levels. This makes it a powerful tool for sampling deeply nested elements. For example, to select all element <div> that contain <p>, which in turn contain <a>:
div:has(p:has(a)) {
text-decoration: none;
}
:has() — Practical Examples
/* Highlight all quotes <q> that appear within a paragraph <p> */
p:has(q) {
background-color: #fff;
border-left: 1px solid #888;
padding: 15px;
}
/* Hide all empty <div> */
div:has(:empty) {
display: none;
visibility: hidden;
}
/* Highlight the link <a> within the footnotes <sup> */
sup:has(a) {
color: #0066cc;
text-decoration: underline;
}
Grouping Selectors
Selectors are often grouped together for better code readability. For example, there is a code:
h2 {
text-align: center;
color: red;
}
h3 {
text-align: center;
color: red;
}
span {
text-align: center;
color: red;
}
It can be shortened by grouping the selectors and written like this:
h2, h3, span {
text-align: center;
color: red;
}
How Browsers Read CSS Selectors
The browser reads selectors from right to left. For example:
#main .article p {
color: red;
}
It will first find all <p>, then select only those that lie inside .article, and then leave only those <p> that lie inside #main.
This seems illogical, but the reason for this behavior is that the tasks of a developer and a browser are slightly different. The task of the developer is to obtain a suitable set of elements. It's more difficult with a browser.
Before rendering the page, the browser builds a mapping tree (render tree). It consists of display objects — visual elements of the page, arranged in the order in which they should be displayed on the page. The mapping tree is built based on DOM, but it does not include non-visual or hidden elements like the <head> tag or elements with display: none, but complex elements like <select> can match multiple display objects.
Page display is performed in several stages, but we are interested in only one - layout of display objects. In this step, the browser traverses the mapping tree and calculates the size and position of each object on the page. To calculate these values for an object, the browser needs to know the styles that are applied to that object. To do this, it needs to find in the style sheet all the rule blocks that apply to the element corresponding to the display object.
The key difference is that the developer needs to find the appropriate elements for the CSS selector, while the browser needs to find the appropriate CSS selectors for the element. In this case, it is much more efficient for the browser to read the selector from right to left, to weed out most of the inappropriate selectors at once.
Consider the example above. Suppose the browser needs to determine whether this selector matches the <div> element. If the browser were to read the selector from left to right, it would have to find the id="main", inside it find all elements with class .article, and only then find all <p> inside it and check whether there is the same <div>. It's too much work. And thanks to reading from right to left, the browser can immediately determine that <p> and <div> are fundamentally different elements and therefore the selector is not suitable.
Inheritance in CSS
Margins and borders, among other properties, are not inherited by nested elements. Suppose the <body> has red text and a paragraph (<p>) has green text. If that paragraph contains a <strong> element, what color will its text be? It will be green: the paragraph’s color is inherited by <strong>, taking precedence over the more distant <body> color. In general, when an element has no explicitly set value for an inheritable property, it uses the value from its nearest ancestor.
body {
font-family: Arial, Helvetica, sans-serif;
color: red;
}
p {
/* This color will be applied to <strong>, which is located inside <p> */
color: green;
}
If there is a CSS style that defines the text color for the table <table>, and another one that defines a different color for cell <td>, then the elements nested in the cells of this table (<td>) — paragraph, heading, bulleted list elements — will inherit the style color <td> because it is the closest ancestor.
A hyperlink inside a paragraph whose text is formatted in red font will still be displayed in the browser window in blue with an underline. This is because there is a custom, predefined style for the binding element <a>. This way, the inherited text color will not be applied. That is, you need to style the links separately: a {color: black;}.
<head>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
color: red;
}
p {
color: green;
}
strong {
font-size: 24px;
}
</style>
</head>
<body>
<!--Here, the link text will remain blue, which is the default. Although all the rest of the text will be green. The font-family property will still be inherited..-->
<p>
Text <strong>text</strong>, text <a href="https://site.com/">LINK TEXT</a>.
</p>
</body>
Can be done as follows. Here the link text will be orange.
<head>
<style>
body {
color: red;
}
p {
color: green;
}
a {
color: inherit;
}
.my-link {
color: orange;
}
</style>
</head>
<body>
<p>
Text <strong>text</strong>, text <a class="my-link" href="https://site.com/">LINK TEXT</a>.
</p>
</body>
CSS Selector Specificity: The Cascade, Weight, and Priority
All CSS selectors have their own weight, which determines how the same properties set in different places of the code of the same element interact.
Sometimes this can cause difficulties when a property declared lower in the code overlaps with a property declared higher, because the former's selector is more specific (has more weight).
Properties of the closest to the formatted element, the most specific style, prevail.
Conflict resolution: the last style wins.
However, it is not always clear which of the selectors is the most specific. CSS offers a prioritization method for this. It is based on assigning values in conditional units to each type of selector: tag selectors, classes, identifiers, etc.
- Generic selector (
*) has a specificity of 0 conditional units. - Tag selector (
p,body,div, ...) has 1 conditional unit. - Class (
.class) — 10 conditional units. - Attribute (
[attr=value]) — 10 conditional units. - Identifier (
#class) — 100 conditional units. - Inline (Inline) style (
style="color: red;") — 1000 conditional units.
The higher the numerical value, the higher the specificity (significance) of this type of selector. Let's say you created three styles:
- the tag style for the element
<img>(specificity = 1); - class named
.highlight(10); - identifier named
#logo(100).
The web page contains the following HTML code:
<img id="logo" class="highlight" src="logo.gif">
If the same attribute is defined in all three styles (for example, the border property), then the identifier style (#logo) as the most specific will be applied.
p .email {
color: blue;
}
.byline a {
color: red; /* This style will be applied because it is specified last in the style table. */
}
<p class="byline">Created by <a class="email" href="mailto:test@site.com">Mykhailo Petrov</a></p>
Now imagine that the two styles are swapped and the stylesheet looks like this:
.byline a {
color: red;
}
p .email {
color: blue;
}
In this case the link will be blue. The style with selector p .email is located in the table after the line .byline a, so its properties have an advantage.
Another example:
#class-3 {
color: green;
}
.class-1 {
color: red;
}
.class-2 {
color: blue;
}
<div class="class-1 class-2">
<!--
The block will be blue because .class-1 and .class-2 have the same priority (specificity). Therefore, the one listed lower in the CSS styles is applied.
-->
</div>
<div class="class-2 class-1">
<!--
The block will be blue because .class-1 and .class-2 have the same priority (specificity). Therefore, the one listed lower in the CSS styles is applied.
-->
</div>
<div class="class-1 class-2" id="class-3">
<!--
The block will be green. Selection by id takes precedence over .class-1 and .class-2.
-->
</div>
<div class="class-2 class-1" id="class-3">
<!--
The block will be green. Selection by id takes precedence over .class-1 and .class-2.
-->
</div>
<div style="color:hotpink;" class="class-2 class-1" id="class-3">
<!--
The block will be pink. The inline style has higher priority.
-->
</div>
Resetting Specificity
Cascading stylesheets allow you to completely cancel style specificity. You can use this technique so that no other more specific style overrides a particular property of a web page element. To do this, insert the value !important.
Let's consider an example. Let there be two styles:
.nav a {
color: red;
}
a {
color: blue !important;
}
By default, a link inside an element with the .nav class would be red because the .nav a selector is more specific than the <a> type selector. Adding !important to the color declaration gives it higher priority, so all links on the page—including those inside .nav—appear blue.
Note that !important applies to an individual property, not the entire style, so you need to add the word !important at the end of each property that should not be overridden.
When the !important directive is specified for two identical properties of different styles, the specificity rule takes effect again, and the priority is given to the more specific attribute of the specified ones.
Be careful when applying
!important. Because this method is cardinal, using it too often will cause your styles to not conform to normal cascading rules, resulting in "escalating" usage of the!important. In other words, to compensate for the specificity of a property with!importantin one style, you would use it in another. Then, to compensate for the action!importantin the second style, you will have to add it to the third style, etc. Therefore, I do not recommend using!importanttoo often. Before adding this directive, try another way to resolve the conflict, such as renaming or swapping the styles in the table.
How to Visualize the Cascade on a Web Page
On the right side of the DevTools panel, you will see the styles applied to a specific element. This is usually the final style, i.e. the summary of all CSS properties applied to the element through inheritance and cascading. A little further down it will show the style rules applied to the element, listed in order from more specific (at the top of the list) to less specific (at the bottom of the list). Most likely, you will see that some properties are crossed out in the list of styles. This indicates that these properties either do not apply to the element or have been overridden by a more specific style.
What Happens When External and Internal Stylesheets Conflict?
In this case, the sequence of their placement on the web page (in the HTML code of the file) is important. If you first add an internal table using the style and then join the external table using the link, then the style of the latter will be applied. Conclusion: Be consistent in referencing an external style sheet in your web page code. It should be attached first, and only then should internal styles be added, unless it is absolutely impossible to do without one or more styles applied to the same page.
Practical Examples
Ready-made solutions that I use in my work.
Add Right Spacing to Every List Item Except the Last (Example 1)
<ul class="menu__list">
<li class="menu__item"><a href="" class="menu__link">Home</a></li>
<li class="menu__item"><a href="" class="menu__link">Product</a></li>
<li class="menu__item"><a href="" class="menu__link">Pricing</a></li>
<li class="menu__item"><a href="" class="menu__link">Contact</a></li>
</ul>
.menu__item:not(:last-child) {
margin: 0px 21px 0px 0px;
}
Add Right Spacing to Every List Item Except the Last (Example 2)
<form class="form" action="/" method="POST">
<div class="form__group">
<p>Name</p>
<input class="input" type="text" placeholder="Mykhailo">
</div>
<div class="form__group">
<p>Phone</p>
<input class="input input--dark input--phone" type="tel" placeholder="+380 XX XXX-XX-XX">
</div>
<div class="form__group">
<p>E-mail</p>
<input class="input input--dark input--email" type="email" placeholder="Example: petrov@example.com">
</div>
<div class="form__group">
<p>Message</p>
<input class="input input--dark input--message" type="text" placeholder="Write your message"><!-- Here, the indentation at the bottom needed to be removed -->
</div>
<button class="form__btn" type="submit">Send</button>
</form>
/* Last form__group form block, before submit button */
.form__group:last-of-type input {
margin-bottom: 0;
}
Styling Form Placeholders
input[type="text"]::-webkit-input-placeholder,
input[type="text"]::-ms-input-placeholder,
input[type="text"]::-moz-placeholder,
input[type="text"]::placeholder {
// do something
}
Select the First Child Element, Regardless of Type
<div class="footer__contacts">
<p>2942 Westheimer Rd. Santa Ana, Illinois 89486 </p>
<a href="tel:+380957777777">+38 (095) 777 77 77</a>
</div>
/* The element will be indented at 34px. */
.footer__contacts > *:first-child {
margin-right: 34px;
}
Select All Children of a Block When They Have No Separate Classes
<div class="parent-block">
<li></li>
<li></li>
<a></a>
<div></div>
</div>
/* All child elements of a parent block with class parent-block will be given a right indent of 10px. */
.parent-block > * { /* or parent-block * */
margin-right: 10px;
}
How to Style Links Without a Class
I will show how to correctly apply CSS styles only to those links<a> that do not have a class without affecting others that are styled through classes.
Why Is This Useful?
When developing a site, situations occur when:
- part of the links are processed through specific classes;
- others remain "clean", i.e. without a class;
- only those without a class need to be styled, such as automatically generated CMS, content from the editor, or third-party content.
This is convenient when it is not possible to add a class manually, but you still need to set the basic style.
I will show the implementation immediately with an example. Let there be markup
<a class="top-menu__item" href="#">Page 1</a>
<a class="footer-menu__item" href="#">Page 2</a>
<a href="#">Page 3</a>
It has only the first two tags <a> have classes. To access the latter, you can simply exclude the selector on the attribute "class".
.top-menu__item {
color: red;
font-size: 16px;
}
.footer-menu__item {
color: black;
font-size: 25px;
}
/* Classless reference */
a:not([class]) {
color: green;
font-size: 45px;
}
Result:
- Page 1 — red, 16px;
- Page 2 is black, 25px;
- Page 3 is green, 45px because it is classless.

How Does It Work?
The a:not([class]) means:
"apply style to all tags
<a>that have noclassattribute at all".
This:
- does not affect references with any class;
- is guaranteed to work even if the class is empty (
class=""— will not pass because the attribute already exists); - works in all modern browsers.
Clarification: What Does Not Count?
<a class="" href="#">Empty class</a> <!-- will not be styled! -->
Link from class="" will not fall under the selector :not([class]) because the attribute exists. If you need to cover these as well, you can use:
a:not([class]), a[class=""] {
/* styles for classless links */
}
Or more universally:
a:not([class*=""]) {
/* style only for those with no class at all or with an empty class */
}
This approach is convenient to use for basic styling of content that does not lend itself to manual processing.
Selectors:not([class])or combinations witha[class=""]will help to cover the maximum number of cases.
CSS Pseudo-classes for Element States: :hover, :focus, and :active
These pseudo-classes give elements a state that is determined by certain actions of the site visitor. For example, states change the color or size of an element, add a border to it to make it more interactive, visually distinguish it, and indicate its purpose.
Key States of Interactive Elements
There are 3 main states.
:hover
Fires when the user hovers over an element. Usually used to create an effect of interaction with an element. For example, when you move the mouse over a link, the color of its text changes.
:hovercan be overridden by other reference-specific pseudoclasses such as:link,:visitedand:active.
Web developers use this approach to highlight links in the content of the publication, highlight items in the main menu of the site. As a result, the user intuitively understands that such an element can be clicked and get a certain result.
<nav class="nav">
<ul class="nav__list">
<li><a class="nav__link" href="#">Main</a></li>
<li><a class="nav__link" href="#">About</a></li>
<li><a class="nav__link" href="#">Contacts</a></li>
</ul>
</nav>
.nav__link {
color: #000000;
}
.nav__link:hover {
color: red;
}
:focus
Engages when clicking on an element or moving to it from the keyboard using the [Tab] key. Applies to all interactive elements (<button>, <a>, <input>, <select>) and elements with tabindex.
There is also a state
:focus-visible, which occurs only when focusing from the keyboard. It improves the accessibility of the site for users with disabilities. If a person moves between sections of the site using the keyboard, it is important for him to understand where he is. Therefore, it is recommended to make the focus state as visible as possible.
<nav class="nav">
<ul class="nav__list">
<li><a class="nav__link" href="#">Home</a></li>
<li><a class="nav__link" href="#">About us</a></li>
<li><a class="nav__link" href="#">Contacts</a></li>
</ul>
</nav>
.nav__link {
color: #000000;
}
.nav__link:focus {
color: green;
}
:active
The :active fires when the user interacts with the item. For example, when holding down the mouse button on an element. Often used to create the effect of clicking a button or link. Pseudoclass :active may not vary much in color because the user knows which element they are interacting with.
The
:activepseudoclass is more commonly used with<a>and<button>but can also apply to other elements (such as form elements).
This state can be overridden by any other reference pseudoclasses (:link,:hover,:visited).
To style the desired links, the:activerule must be placed after all other rules related to the link, as defined by the LVHA-order rule::link—:visited—:hover—:active.
<nav class="nav">
<ul class="nav__list">
<li><a class="nav__link" href="#">Home</a></li>
<li><a class="nav__link" href="#">About us</a></li>
<li><a class="nav__link" href="#">Contacts</a></li>
</ul>
</nav>
.nav__link {
color: #000000;
}
.nav__link:active {
color: yellow;
}
How Element States Affect Accessibility
Not all users use a mouse, so it is important that the site can be navigated using a keyboard or other alternative devices.
It is recommended to specify the states :hover, :focus and :active for all interactive elements that the user interacts with. This allows you to create an accessible and understandable interface for him, thanks to which the visitor will stay longer on the site and return.
In feedback forms, the :focus pseudo-class highlights the active field when navigating with the keyboard. This helps users with disabilities fill out the form correctly.
When element states are different, it's easier for the user to understand where the link is and where the focus is now. It is better for links to specify different colors for :hover and :active so that the user can distinguish which item is selected.
That's why it's not always a good idea to write all states together:
.nav__link:hover,
.nav__link:focus,
.nav__link:active {}
Also, different browsers and operating systems may display different states, so this code will not work perfectly. It is better to separate the states and style each of them separately:
.nav__link:hover {}
.nav__link:focus {}
.nav__link:active {}
Element states can also be used to create animation effects and visual changes on a site. For example, when hovering over a picture of a product, you can increase its size or add a shadow effect.
