Can you explain the purpose of *:before and *:after in CSS?

After conducting research on Stack Overflow regarding the use of the asterisk symbol (*), I discovered that it selects all elements and applies styles to them.

By following this link on Stack Overflow about the Use of Asterisk, I found out that using the code provided below will apply a red border to all elements.

* {
 border: 1px solid red;
}

My current question is, what exactly do *:before and *:after do in CSS?

*:before,
*:after {
          box-sizing: border-box;
}

Answer №1

According to their name, :before & :after are utilized to implement css properties IMMEDIATELY before or after the content INSIDE the corresponding element.

There is a saying attributed to a sage that goes 'A single demonstration speaks volumes', and so:

div {
  border: solid 1px black;
  padding: 5px;
  }

div:before {
  content: "Added BEFORE anything within the div!";
  color: red;
 }

div:after {
  content: "Added AFTER anything within the div!";
  color: green;
 }
<div>Div 1</div>
<div>Div 2</div>
<div>Div 3</div>
<div>Div 4</div>

Answer №2

The magic of the :before selector is that it has the power to insert content before each selected element or elements, while the :after selector does the same but after the content.

As Dan White cleverly pointed out, *:before will add content before all elements, creating a stylish introduction, and *:after will follow up with content placed after all elements for a well-rounded finish.

Answer №3

:after is a pseudo element that allows inserting content onto a webpage using CSS without the need to include it in the HTML code directly. Although the outcome is not physically part of the DOM, it visually appears as if it is included in the page layout, like this:

div:after {
  content: "hi";
}

<div>
  <!-- Other elements inside the div -->
  hi
</div>

:before functions similarly to :after, but places the content before the existing HTML content instead of after it. The decision to choose one over the other typically depends on:

  • You intend for the added content to appear before the existing content.
  • The :after content is also positioned after the ::before content in the source order, meaning it will overlay ::before when stacked naturally.

The content value can be:

  • A string: content: "a string"; - special characters must be encoded as unicode entities for display. Review the glyphs page for more information.
  • An image:
    content: url(/path/to/image.jpg);
    - Images are inserted at their actual dimensions and cannot be resized. Pseudo elements can serve to create gradients since they are essentially images too.
  • Nothing: content: ""; - Beneficial for clearfix techniques and adding images as background-images (with specified width and height that may be resizable with background-size).
  • A counter: content: counter(li); - Ideal for styling lists until :marker support becomes available.

Please note that injecting HTML content directly into the pseudo element's content property like <h1>nope</h1> won't render as expected.

Answer №4

It is affirmed that all pseudo elements will exhibit the identical box model characteristics as regular elements within your document object model. ::before and ::after serve as pseudo elements, indicating they do not exist in the DOM and are unselectable with a mouse.

Answer №5

Utilizing pseudo-element selectors like :before and :after (or ::before and ::after) allows for the generation of dynamic content in browsers, known as generated content. This content is not part of the document's DOM, making it invisible to tools like screen readers.

This feature acts like a template; for example, it can be used to insert icons before list items, display URLs next to links when printed, or add appropriate quotation marks around quotes based on language.

For a practical demonstration, check out this fiddle:

ol.warning::before {
  background-image: url('https://i.postimg.cc/bYW5CQF7/6897039.png');
  background-size: 20px 20px;
  display: inline-block;
  width: 20px;
  height: 20px;
  content: "";
}

ol.warning::after {
  content: "   (This is very important!)";
  color: red;
}
<ol class="warning">Having No Regular Checkups</ol>
If you make regular checkins at the gluten free aisle, but not with your doctor, that needs to change.  Checking your health with a weigh in, stress test, and blood workup is critical.

<ol class="warning">Leading A Sedentary Lifestyle</ol>
If you spend most of the day sitting and don’t have an exercise plan or routine, time to take action.  Get a plan for daily movement and make sure weights are part of the equation.

<ol class="warning">Eating Too Much </ol>
If you sure your microwave plastics are BPA free, but fill them with too many calories of processed food, time to count calories.  While you are at it, make sure your food comes from good sources and drink more water.

<ol class="warning">Staying Sleep Deprived</ol>
If you are tired, that is not a badge of honor.  That is a health hazard sign of the highest importance. Get 8 hours a night, don’t hit the snooze button, and get away from your phone an hour or more before bedtime.

<ol class="warning">Texting And Driving</ol>
No LMAO text or snapchat streak is worth your health or the health of someone else.  Learn to view this as important as fastening your seatbelt.

<!-- content from https://www.trainingforwarriors.com/the-20-most-dangerous-things-you-are-still-doing/  -->

You have the flexibility to update the template content collectively rather than individually for each point, allowing for easy modifications when needed.

References:

  1. Learning Web Design: A Beginner's Guide to HTML, CSS, JavaScript, and Web Graphics
  2. Learning To Use The :after And :before Pseudo-Elements In CSS

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the background color of a specific list item when hovering over another list item

My dilemma lies in my inadequate knowledge to solve this issue: I have a dropdown menu embedded within a website. (View screenshot here: [SCREENSHOT]) The desired outcome is for the background color of an icon on the main list to change when I navigate to ...

Struggling to dynamically incorporate multiple tagit fields into my project - hitting roadblocks at every turn

I am facing an issue with adding a tagit field dynamically using a button click. The data is appended correctly, but the tagit feature does not work as expected. Instead of converting the ul to a tagit field, it adds blank ul. I wonder why this is happenin ...

Align a Font Awesome icon vertically within a table cell that has a dynamic height

How can I vertically align a font-awesome icon in the center of a td? The td may have varying heights due to its content, which could be one or two lines of text. I've tried adjusting the line-height, using vertical-align, and even applying display: i ...

What is the best way to design a responsive menu that is perfectly centered?

I'm facing challenges with designing a menu that includes 4 items, needs to be centered next to each other with spacing in between, and should stack vertically on mobile devices. The desired look for the menu can be viewed in this image... https://i. ...

Stylesheet failing to respond to CSS Media queries

I have looked at other questions with similar issues and it appears that what's missing in their code is: <meta name="viewport" content="width=device-width, initial-scale=1"> However, I already have this code implemented but still facing probl ...

The placement of the breadcrumb trail is not in the right position

My website includes a menu and breadcrumbs. The menu consists of two submenus: Design Services, Design Portfolio, Design Fees, About Us, Contact Us, Design Resources, Design Vacancies, and Terms. Clicking on Design Services reveals Graphic Design, Logo Des ...

Assigning a unique identifier to a button that will vary depending on the selected radio input

UPDATED HTML: The circumstances have changed because I am no longer in my office, but the concept remains unchanged. The situation is that on a certain part of a website, users have the option to choose from multiple saved addresses. Each address has a un ...

Updating image content on the fly in a popover

Here is my unique HTML code: <div class="col-12 custom-file" data-toggle="popover-hover"> <input type="file" id="fileUpload" class="custom-file-input" accept=".jpg,.png,.jpeg"> < ...

Ways to troubleshoot the MudTabPanel during scrolling

I am trying to create a fixed text at the top of a scrollable MudTab. As I scroll down, I want the text to remain visible. Here is an example of what I have done: <MudTabs Position="Position.Top" PanelClass="pt-2" Style="hei ...

Insects featuring a button and tooltip duo creating a captivating "pull-effect"

Why is the button pulling when I move the cursor over a camera? Is there a way to solve this issue? <div class="input-group-btn advanced-group"> <button class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Send Imag ...

Create a React MUI component that allows menu items to become sticky when selected

Is there a way to make the mui MenuItem stay sticky to Select while scrolling down? To see the issue in action, check out this codesandbox example https://codesandbox.io/s/quirky-knuth-5hr2dg?file=/Demo.tsx Simply click on the select and start scrolling ...

Creating a variable in JavaScript

In my HTML body, I have set up a global variable named index with the value <%var index = 0;%>. This allows me to access it throughout the code. I'm trying to assign the value of $(this).val() to <% index %>, but I can't seem to get ...

What is the best method for inserting content into a custom element as input for the component?

Currently, I am in the process of creating a syntax highlighting web component that will be able to highlight any content placed inside it. Let me illustrate with an example code snippet: <fs-highlight data-line-numbers="true" data-language=&q ...

PHP: A Guide to Creating Lists with Subheadings

Recently ventured into the world of PHP, my current project involves creating a dynamic list using PHP and MySQL database as shown below: -----my specific output requirements ------ Main Page Heading Subheading1 (Content for brandtype=1) 1111 2222 33 ...

Is there a method or API available for interacting with an <object> that is currently displaying a video?

Yay, I figured it out! I've been using video.js to play videos on a website that needs to work offline too. Unfortunately, using flash is not an option due to compatibility issues. So, I decided to write my own fallback solution. For Internet Explor ...

Navigating through Frames using Selenium in C#

I am facing an issue with using Selenium on this site. The elements I need to interact with are within a 'frame' that is inside a 'frameset'. Here is the relevant HTML snippet: <frameset rows="0%, 95%" frameborder="0" frameSpacing=" ...

Is there a way for me to display a FontAwesome spinner on a button?

My HTML code utilizes Bootstrap and FontAwesome. Here is an example: <button type="submit" class="btn btn-primary"> <i class="fas fa-spinner fa-spin" style="display:none;"></i> ...

Objects Drop Beyond the Visible Screen

After running my webpage through Google's PageSpeed Insights for analysis, I received a detailed report which can be viewed here The aspect that is puzzling me is the "Size content to viewport" feedback provided in the "User Experience Beta" Section. ...

Ways to center text both vertically and horizontally within a container

Is it possible to align text both vertically and horizontally in the center within a container without relying on flexbox or absolute positioning? Can this be achieved using only text-align:center and vertical-align:center? Under what circumstances would ...

Issue with WordPress Body Class not being implemented

Attempting to create templates for the WordPress theme Flexform, I have successfully created a specific page with a custom header. Surprisingly, there was no need to include a body_class call as it was already present: <body <?php body_class($page_c ...