What's new
HTML Forums | An HTML and CSS Coding Community

Welcome to HTMLForums; home of web development discussion! Please sign in or register your free account to get involved. Once registered you will be able to connect with other members, send and receive private messages, reply to topics and create your very own. Our registration process is hassle-free and takes no time at all!

[TIPS] ::before and ::after content

Koyyiko

New member
Many of the elements on your website will be redundant. For example, you might have a standard font size for the H2 element throughout the page or even the website. To avoid repetitive code, we utilize CSS and apply the style in a single place. However, developers are hardly pleased with a single element. They come up with creative methods to make each element stand out. This results in unique designs, as shown below.

H2 element throughout


Another example of such a design is shown below.

Another example of such a design is shown below.


Hard coding these styling elements (read and stylish quotes) repeatedly on each element is not a good practice. Even if someone wants to change the color of the quotes, it is tough to make the changes on hundreds of quotes you already designed.

Putting something before or after any element in HTML is taken care of by :: before and ::after pseudo-elements of CSS.

Let’s say I want to put the location in front of all the news headlines and a “read more” text after the content. I can proceed in the following direction:

Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Absolute Numbers</title>
  </head>
  <style>
    #texas::before {
      content: "texas";
      font-size: 12px;
      color: orange;
    }
 
    #washington::before {
      content: "washington";
      font-size: 12px;
      color: orange;
    }
 
    .news::after {
      content : "Read More...";
      color: red;
    }
  </style>
  <body>
 
    <h2 id="texas">XYZ to hold a new event in texas </h2>
    <p class="news"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
 
    <h2 id="washington">XYZ to hold a new event in texas </h2>
    <p class="news"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
 
 
  </body>
</html>


The output, when rendered on the LambdaTest platform on a VM, looks as follows:

The output


Notice how the location appears “before” the main heading and a “Read More…” sign “after” it. As I have done above, you can also style these components with the font size and color properties.
 
Back
Top