We have discussed CSS selectors in the last three articles in this sereis. We have said that a selector can be a markup element, an attribute selector based on the class and ID attributes, or a structured selector based on the document structure. CSS introduces pseudo elements, which we will be discussing in this article. This is one area of functionality that you can't achieve using HTML, and you will be amazed how easily you can achieve it in CSS.
Learn CSS, part 7: Pseudo Elements - The ::before and ::after Pseudo Elements (Page 6 of 6 )
These pseudo elements give you the ability to insert text or images before (using ::before) the content of the element and after the content of the element (using ::after), through the use of the content property. They are very useful if you have some string values that are repeated in the HTML code a lot. Instead of sending them many times, increasing the size of the page and using more bandwidth, you can send these string values only once in the CSS file (because browsers will cache the CSS file). Use this in Web pages as much as you can, because doing so will save the page size -- but be careful to use generated content, because it has not yet been implemented by IE.
Let's look at an example. In the next CSS code we set the before and after content for any <p> element that has the class QandA (note the power of the combination of element selector, class selector and the pseudo element offered by CSS):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <link rel="stylesheet" href="PElements.css" type="text/css"> <title>CSS Pseudo Elements</title> </head> <body> <p class="QandA">Do you like CSS</p> </body> </html>
The ::before pseudo element has inserted the value of its content property BEFORE the content of the <p> element, and has applied the styling rules too. The same thing applies to the ::after pseudo element.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.