There is now way to use CSS to apply styles to an element based on the number of characters of text it contains - but this is something JavaScript can help us with.
This technique is closely related to selecting elements based on their text content.
Counting characters in innerHTML
for non-form elements:
element.innerHTML.length
Counting characters in value
for form elements:
element.value.length
Counting characters in either innerHTML
or value
:
element.textContent.length || (element.value && element.value.length) || 0
Selecting elements based on the text content using XPath with the text()
function:
@element .min-characters and (min-characters: 35) {
$this {
background: greenyellow;
border-color: limegreen;
}
}
@element .max-characters and (max-characters: 35) {
$this {
background: greenyellow;
border-color: limegreen;
}
}
.min-characters[test="this.innerHTML.length > 5"] {
background: lime;
}
.min-characters-form[test="this.value.length > 5"] {
background: lime;
}
.max-characters[test="this.innerHTML.length < 5"] {
background: lime;
}
.max-characters-form[test="this.value.length < 5"] {
background: lime;
}
/* Min-characters: 5 */
[xpath="//div[string-length(.) >= 5]"] {
background: lime;
}
/* Max-characters: 5 */
[xpath="//div[string-length(.) <= 5]"] {
background: purple;
}