CSS Pseudo Elements are useful for adding special effects to selectors, which would be difficult to achieve if we were to use real markup. For eg: styling of the first letter or first line of a paragraph. In a previous article, I had introduced the CSS First-Letter First-Line Pseudo Elements. In this article, we will take a quick overview of two more pseudo elements: ::after and ::before
Note: Pseudo elements are not new to CSS3. They were introduced in CSS2. In CSS3, you use double colon (::) for pseudo elements to differentiate them with pseudo classes.
The ::after and ::before pseudo elements are used to apply styles and generate content and insert it at the beginning and end of existing elements.
::before Pseudo Element
For e.g: Let us see how to insert text in front of every list item <li>. In this example, we are inserting text ‘Bakery Item’ in front of each <li> element.
Let us first declare an unordered list as shown below:
Now use the ::before pseudo element to add the text ‘Bakery Item’ to each li element
<head> <title>after and before pseudo elements - DevCurry.com</title> <style type="text/css"> ul.bake li:before { content: "Bakery Item: "; font-style:italic; } </style> </head>
OUTPUT
::after Pseudo Element
Similarly, let us say we want to add an image after each list item, like a green arrow that indicates that the item is available. Here’s how to do this using the ::after pseudo element. I have kept an image called ‘yes.jpg’ in the same folder as that of the html file
<head> <title>after and before pseudo elements - DevCurry.com</title> <style type="text/css"> ul.bake li:before { content: "Bakery Item: "; font-style:italic; } ul.bake li:after { content: " " url("yes.jpg"); } </style> </head>
OUTPUT
Tweet
1 comment:
Thanks! This pointed me in the right direction. I was looking to add a small triangle after a list item to indicate that item was a dropdown using :after. I couldn't get it to work until I added content:"" url("image"); after reading this. Thanks again!
Post a Comment