CSS selector that matches every element containing text
CSS Selectors to Match Every Element Containing Text
In this article, we’ll learn how to use CSS selectors to match every element containing text. CSS is a language used to describe the style and layout of web pages, and CSS selectors are used to select specific elements to apply styles to.
Read more: CSS Tutorial
Matching Elements Containing Text
In CSS, there are several ways to select elements that contain text. Here are some commonly used selector examples:
1. :contains()
Pseudo-Class Selectors
The :contains() pseudo-class selector can be used to select elements that contain specific text. For example, if we want to select all elements that contain the text “Hello World”, we can use the following CSS rule:
:contains('Hello World') {
/* Style rule */
}
2. :empty Pseudo-Class Selector
The :empty pseudo-class selector can be used to select empty elements that do not contain any text or HTML elements. For example, if we want to select
<
div> elements that have no content, we can use the following CSS rule:
div:empty {
/* Style rules */
}
3. :nth-child() Pseudo-Class Selector
The :nth-child() pseudo-class selector can be used to select elements with a specific text number. For example, if we want to select the second
element containing text, we can use the following CSS rule:
p:nth-child(2) {
/* Style rules */
}
4. :not() Pseudo-Class Selector
The :not() pseudo-class selector can be used to select elements that do not contain specific text. For example, if we want to select all elements that do not contain the text “Hello World”, we can use the following CSS rule:
span:not(:contains('Hello World')) {
/* Style rule */
}
Example Description
Let’s take a look at an example. Suppose we have an HTML page that contains multiple
elements and one element. We want to select and apply styles to the
element that contains the text “CSS Selector”
We can use the following CSS rule:
p:contains('CSS Selector') {
color: blue;
}
In the above example, all elements containing the text “CSS Selector” will be set to a blue font.
Summary
In this article, we introduced several CSS selectors that can be used to select elements containing text. By using pseudo-class selectors such as :contains(), :empty, :nth-child(), and :not(), we can easily select and apply styles to elements containing specific text. Understanding and flexibly applying these selectors will help us better control and manage web page styles and layouts.