CSS ::after and ::before the friends you want to know

June 18, 2021
CSS

Usually when we are doing fronted development and we need to add something like this:

 

CSS

 

We can think that by simply adding a span tag with a class and give the styles we need we are done. But sometimes we do not have the ability to add new tags or HTML markup, maybe we are working on Drupal and add the new label may be more laborious than it looks, then it's time for you meet ::before and ::after. ::before and ::after are used to give styles to specific parts of an element and in combination with the content CSS property, they will be a powerful a add pro styles touches to your CSS and have a useful tool under the sleeve. Now let's see our friends in action, as their names indicates ::before adds a new element before the element that is being applied, ::after does the same only it adds the element after it. It is important to note that you can only use ::before and ::after once per element.

 

With this in mind we can do things like: h1::before { content: url(smiley.gif); // adds an image before the h1 tag } We can go a little further and do things like: h1 ::before { content: ''; background-color: #64b8dd; display: inline-block; height: 20px; padding-right: 5px; width: 20px; } With this we add a square with a blue background color and a bit of padding right for the square does not appear right beside the text of the h1 tag. These pseudo-elements can be treated as any HTML element to which we can add properties like background, position, display, content sources can also be used to add icons using content: "\2713"; which when having the “Roboto” font it will render a check icon getting the result we are looking for in the previous image. The disadvantages of using ::before and ::after is that they are not supported by older browsers. List of the ones that support it: 

 

CSS

 

Before you start to use ::before and ::after in all the elements you want, there are some elements that they do not work on, these are Replaced Elements, which are elements whose dimensions and appearance are determined by external agents. The pseudo-elements do not apply to them because they may not have "content" for themselves, or are replaced by something like the user interface. Some of them are: img, iframe, br, hr, object, textarea, input, select, video, audio, canvas. Another thing to mention is that ::before or ::after notation (with two colons) was introduced in CSS 3 in order to establish a discrimination between pseudo-classes and pseudo-elements. Browsers also accept the notation :before or :after introduced in CSS 2. Now you have new technique and can start to add more flavor to your styles and face new challenges.