What is the best way to dynamically incorporate Before After CSS code in Vue?

I am facing a unique challenge in my current project. I need to dynamically apply colors from data inside a v-for loop, specifically for the :after CSS pseudo-element. While normal CSS properties are easily applicable, I am struggling with applying styles for :after. Here is what I have tried so far:

<div class="_tmln_shdl_crd_itm" v-for="(t, i) in timeLine" v-if="timeLine.length">
    <div class="_tmln_shdl_itm_lft">
        <p :style="`color:${t.color}`">{{t.time}}</p> // THIS WORKS
    </div>
    <style>
        ._tmln_shdl_itm_r8_one h4:after{ // ATTEMPTED TO WRITE CSS WITH FOR LOOP BUT FACED DIFFICULTIES
                color: t.color
         }
    </style>
<div>

Can anyone suggest how I can successfully style ._tmln_shdl_itm_r8_one h4:after? I appreciate any solutions or insights. Thank you.

Answer №1

Each time you create a style within the loop, it generates CSS for the same selector. The browser will only apply one set of CSS styling to that specific selector.
In the case of the same selector, the most recent CSS will override and be used. This concept is known as CSS Specificity ("When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element.").

You have the ability to dynamically create classes:

<div class="_tmln_shdl_crd_itm" v-for="(t, i) in timeLine" v-if="timeLine.length">
    <div :class="`_tmln_shdl_itm_lft _tmln_shdl_itm_lft-${i}`">
        <h4>{{ t.time }}</h4>
    </div>
    <style>
        ._tmln_shdl_itm_lft-{{ i }} h4:after{
            color: {{ t.color }};
        }
    </style>
<div>

An approach like this should suffice. By making the class dynamic with ._tmln_shdl_itm_lft-{{ i }}, you can achieve the desired effect.
However, this method may lead to an abundance of unnecessary CSS on the page, which might not be ideal for a live environment.

Points to note:

  • In addition, ensure that you output t.color correctly as shown below (likely just an oversight in your example):
    color: {{ t.color }};
  • It appears that there is no h4 tag present in the provided code snippet where the CSS can be applied, but presumably, it exists elsewhere on your page... hopefully?

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

What is the best way to arrange an array of words expressing numerical values?

Is there a way to alphabetize numbers written as words (one, two, three) in Javascript using Angularjs? I need to organize my array of numeric words $scope.Numbers = ["three", "one", "five", "two", ...... "hundred", "four"]; The desired output should be ...

Error encountered during sequelize synchronization: SQL syntax issue detected near the specified number

Four Sequelize Models were created using sequelize.define();. Each model is similar but with different table names. To avoid manual creation of tables in MySQL cli, the decision was made to use sequelize.sync() in the main index.js file to allow Sequelize ...

"Embracing Progressive Enhancement through Node/Express routing and the innovative HIJAX Pattern. Exciting

There may be mixed reactions to this question, but I am curious about the compatibility of using progressive enhancement, specifically the HIJAX pattern (AJAX applied with P.E.), alongside Node routing middleware like Express. Is it feasible to incorporate ...

:after pseudo class not functioning properly when included in stylesheet and imported into React

I am currently utilizing style-loader and css-loader for importing stylesheets in a react project: require('../css/gallery/style.css'); Everything in the stylesheet is working smoothly, except for one specific rule: .grid::after { content: ...

Guide on transferring files between Node.js/Express servers from receiving files at Server A to sending files to Server B

Currently, I'm tackling node.js express servers and I've hit a roadblock! Despite my efforts to scour the documentation and other resources, I can't seem to find the right solution. Here's what I need to accomplish: Receive 2-3 PDF ...

Insufficient allocation - memory overflow in loopback.js

I encountered an issue while trying to fetch large data using loopback.js. The error message I received was: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory <--- Last few GCs ---> 45903 ms: Mark-sweep 1385.6 (14 ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

Error encountered when attempting to assign a value of the original data type within the Array.reduce function

I am in the process of developing a function that takes a boolean indicator object like this: const fruits = { apple: false, banana: false, orange: false, mango: false, }; Along with an array such as ['apple', 'orange']. The go ...

Managing the rendering of charts in Angular with Directives

I'm in the process of creating an admin page with multiple elements, each revealing more information when clicked - specifically, a high chart graph. However, I've encountered a challenge with the rendering of these charts using a directive. Curr ...

What is causing my Li elements to be unchecked in REACT?

Why is the 'checked' value not changing in my list? I'm currently working on a toDo app Here are my State Values: const [newItem, setNewItem] = useState(""); const [toDos, setToDos] = useState([]); This is my function: funct ...

Automatically send users to the login page upon page load if they are not authenticated using Nuxt and Firebase

I'm currently facing an issue with setting up navigation guards in my Nuxt application. The goal is to redirect users to the login screen if they are not authenticated using Firebase Authentication. While the router middleware successfully redirects u ...

adjust the placement of data labels based on the height of each column in a vertical bar chart

Utilizing vue chat js along with chart js 2.9.4 package, I've also integrated the chart js plugin datalabels to display data labels. When creating a vertical bar chart, I encountered an issue where some columns' heights were lower, causing the da ...

How to organize initial, exit, and layout animations in Framer Motion (React) tutorial?

Currently, I am utilizing framer-motion library for animating a change in grid columns. This is the objective: Within the grid container (#db-wrapper), there are nine buttons arranged. https://i.stack.imgur.com/61pQqm.png When the user switches to the ...

Tips for transferring data from one tab to another tab using Greasemonkey

Is it possible to extract data from a webpage in one tab and then input it into a textarea on a different page opened in a separate browser tab using Javascript and Greasemonkey? ...

How to use Javascript to pause an HTML5 video when closed

I am new to coding and currently working on a project in Adobe Edge Animate. I have managed to create a return button that allows users to close out of a video and go back to the main menu. However, I am facing an issue where the video audio continues to p ...

How to efficiently eliminate duplicates from an array list using React framework

Keeping the array name constant while duplicating and repeating this process only clutters the list. Appreciate your help. setListItems(contents.data); console.log(contents.data); ...

CSS scoped components do not adhere to styles

Here is a basic component example that I'm working with: <template> <div> <b-form-group label="From:" label-align="left" label-for="nested-from"> <date-pick :displayFormat=&quo ...

Tips for preventing the inheritance of .css styles in React

I'm facing an issue with my react application. The App.js fragment is displayed below: import ServiceManual from './components/pages/ServiceManual' import './App.css'; const App = () => { return ( <> ...

Utilizing the fetch method for sending cross-origin JSON data to an Express backend

When attempting to use Fetch to send JSON data from a form and receive a response from an Express server, I am encountering an issue where I only see an empty object in the console instead of the expected JSON response with the form values. You can find t ...

The button fails to function properly following the initial successful loading of ajax data

var Update = { init: function(){ $('.find').on('click', function(e){ e.preventDefault(); var $this = $(this), $form = $('#searchForm'); BLC.ajax({ ...