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

Can two Angular element components be utilized simultaneously on a single page in Angular 6?

Currently, I'm attempting to host independent Angular elements that can be seamlessly integrated into a non-Angular webpage. Everything works perfectly fine when there's only one element on the page, but as soon as I try to load two or more, I en ...

Is there a way for me to determine if something is hidden?

My goal is to have selector B toggle when selector A is clicked or when clicking outside of selector B. This part is working fine. However, I'm struggling with preventing selector B from toggling back unless selector A is specifically clicked - not w ...

The firebase collection's model doesn't include an add function within its nested collection

I'm currently developing an application where I aim to utilize Firebase for real-time data storage within the context of the Backbone framework. The issue I am facing is as follows: I have a sub-level model and collection, both of which are standar ...

Fetching JSON data from an external URL using AngularJS

Check out this URL that shows JSON data in the browser: I attempted to store the data in a variable with the following code: $http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode& ...

Counting duplicate values associated with the same key in a JSON array using JavaScript/NodeJS

Hello everyone, I could really use some assistance in solving this issue. If this has already been asked before, please direct me to the original question. Currently, I am working with a JSON array of elements. For example: var data = [{"key":"Item1"},{ ...

Extracting a subclass from an array

Currently, I am delving into the world of coding as part of a project I'm working on. Here is an excerpt from my JavaScript code that interacts with Google Maps API: for (i = 0; i < results.length; i++) { console.log("Formatted Address: "+ re ...

Access-Control-Allow-Headers does not permit the use of request header X-CSRF-TOKEN

Currently, I am utilizing Vue and Axios to make a get request to embed.rock. axios({ method: 'get', url: 'https://api.embed.rocks/api?url=' + this.url, headers: { 'x-api-key': 'my-key' } }) Oddly enou ...

Exclusive to Safari: Codesandbox is experiencing difficulties retrieving data from the localhost server

Would you mind helping me out with this technical issue I'm facing? For the server/API, I am using this link. As for the mock website, it can be found at this URL. The problem is that, in my code, I'm using axios to fetch data from the locally h ...

React: Conceal additional elements once there are over three elements in each section

React: I am trying to create a menu with submenus. My goal is to calculate the number of submenus and if it goes over 3, hide the additional submenus. Below is the code snippet for counting the elements: export default function App() { const ElementRef ...

Autocomplete feature integrated within search bar

I'm currently experimenting with merging MUI autocomplete and MUI searchbar to create a Searchbar that provides suggestions. I have attempted the following: https://codesandbox.io/s/material-demo-forked-cthpv import React from "react"; impo ...

Angular mistakenly uses the incorrect router-outlet

Encountering an issue with Angular routing. The main app has its own routing module, and there is a sub module with its own routing module and router-outlet. However, the routes defined in the submodule are being displayed using the root router outlet inst ...

Using a data() object in Vue to fill out form fields efficiently

My data retrieval process from mongodb involves obtaining the data and transferring it to the client side using the following approach: error_reporting(E_ALL); ini_set('display_errors', '1'); require '../vendor/autoload.php'; ...

Is it possible to utilize a React component within the DataGrid cell instead of the standard cell types like 'string', 'number', 'date', and 'dateTime' in Material UI?

Using React, Material UI, and TypeScript I am trying to embed a React component into the cell of a DataGrid but have encountered an issue. I have explored custom column types for cells here, however, it only allows me to manage string formats, whereas I ...

What occurs when you use the statement "import someModuleName from someModule" in JavaScript?

When reusing a module in multiple places, you typically use module.exports = yourModuleClassName to make the module exportable. Then, when you want to use it elsewhere, you can simply import it with import yourModuleClassName from 'yourmodulePath&apos ...

If the next element in the sequence happens to be the final element, then conceal a separate

Continue pressing the downward button consistently on until you reach the bottom. The down arrow should disappear slightly before reaching the end. Is there a way to achieve this using the code provided below? I'm new at this, but I believe I need t ...

Ways to disable the ability to close a bootstrap modal by pressing the backspace key

How can I enable the backspace button in a Bootstrap Modal form for textboxes and textareas? $('body').keydown(function (e) { if ($('#myModal').is(':visible')) { if (e.keyCode == 8) { retu ...

React: automatically close other SubMenus when a new SubMenu is opened

Is there a way to automatically close all other open SubMenus when a user opens a new SubMenu? If anyone has a solution, I would greatly appreciate the help! This is my code: Menu.tsx -> const Menu: React.FC = ({ data }) => { return ( ...

Monitoring AJAX POST progress with Node.js and Multipart: XMLHttpRequest

Is there a way to provide real-time updates on the size of a file being uploaded to a client, similar to how YouTube does it? I've looked into getting the full size of the file with req.files.myFile.size, but is there a method to track the current siz ...

SailsJS fails to transpile Bootstrap.js in a timely manner

In my backend development with Sails JS, I am utilizing ES6/7 and have created a class to handle background tasks. After reading a post on StackOverflow (link), it was recommended to initiate background tasks in config/bootstrap.js. Following this advice, ...

Bootstrap form validation solution

Utilizing bootstrap validation to validate a jsp page. The folder structure is as follows: WebContent ├── bootstrap-form-validation ├── js └── pages All three folders are under the web content. If I create another folder called teacher ...