What are pseudo-elements?
A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). For example, ::first-line can be used to change the font of the first line of a paragraph.
/* The first line of every <p> element. */
p::first-line {
color: blue;
text-transform: uppercase;
}
Note: In contrast to pseudo-elements, pseudo-classes can be used to style an element based on its state.Syntax
The syntax of pseudo-elements:
selector::pseudo-element {
property:value;
}
You can use only one pseudo-element in a selector. It must appear after the simple selectors in the statement.
Note: As a rule, double colons (::) should be used instead of a single colon (:). This distinguishes pseudo-classes from pseudo-elements. However, since this distinction was not present in older versions of the W3C spec, most browsers support both syntaxes for the original pseudo-elements.
Index of standard pseudo-elements
Browser | Lowest Version | Support of |
---|---|---|
Internet Explorer | 8.0 | :pseudo-element |
9.0 | :pseudo-element ::pseudo-element | |
Firefox (Gecko) | 1.0 (1.0) | :pseudo-element |
1.0 (1.5) | :pseudo-element ::pseudo-element | |
Opera | 4.0 | :pseudo-element |
7.0 | :pseudo-element ::pseudo-element | |
Safari (WebKit) | 1.0 (85) | :pseudo-element ::pseudo-element |
How to get text from CSS property “content” on a ::before or ::after pseudo element
Many a Time, we have a requirement to get text contents of a CSS property "content" on a ::before or ::after pseudo element
Below is one of the cool ways to mitigate this situation.
We need to verify the text "This text needs to be verified." is displayed using Selenium WebDriver in Java.
I have the following HTML:
<div id="test_ID">
<ul>
<li>Required: Server Name</li>
<li>Required: Receiving Port</li>
</ul>
</div>
with the following CSS code:
#validationError:before {
content: 'This text needs to be verified.';
}
Key: The sad part is this requirement cannot be only achieved using Java, however, we can always use the little sister of java - javascript(which works with selenium webDriver)
String script = "return window.getComputedStyle(document.querySelector('#test_ID'),':before').getPropertyValue('content')";
JavascriptExecutor js = (JavascriptExecutor)driver;
String content = (String) js.executeScript(script);
System.out.println(content);
This should print: This text needs to be verified