How to apply a CSS style to a specific class based on conditions in Vue.js

Many questions have been asked about conditionally adding classes or styles to elements, but I want to take it a step further and conditionally style a class.

In my application, users can customize foreground and background colors using a theming system. I want to apply these colors to quill.js toolbar buttons dynamically. If I knew the colors beforehand, a simple CSS rule would do the trick.

.ql-toolbar .ql-stroke {
    stroke: #f00;
}

I could even create conditional classes for different color combinations in my stylesheet.

.ql-container.foo {
    .ql-toolbar .ql-stroke {
        stroke: #f00;
    }
}
.ql-container.bar {
    .ql-toolbar .ql-stroke {
        stroke: #b4c;
    }
}

However, since users can choose any RGB color, this approach won't work.

I've attempted adding inline styles to the component template, but encountered compilation issues.

Currently, I'm resorting to using document.querySelector to access the toolbar and manually change button properties based on user color selections. This is a messy solution that doesn't handle dynamic styles like hover states.

Is there a more elegant way to achieve this?

Answer №1

After reading a helpful article, I discovered the solution is to utilize CSS variables and pass them through a style binding.

<template>
   <div class="container" v-bind:style="{'--toolbarColor': toolbarColor}">
      <!-- Quill editor component goes here -->
   </div>
</template>

<style>
    .ql-toolbar {
        background-color: var(--toolbarColor) !important;
    }
</style>

<script>
    export default {
        computed: {
            toolbarColor() {
                return '#f00'; // This sets the toolbar color dynamically
            }
        }
    }

</script>

Answer №2

To achieve this functionality, consider using the styled-components library

If you prefer a quicker setup, you can utilize the vue-styled-components package

const StyledDiv = styled.div`
  flex: 1;
  ${props =>
    props.justifyContent &&
    css`
      justify-content: ${x => x.justifyContent};
    `};
  ${props =>
    props.padd &&
    css`
      padding: 24;
    `};
`;

You can then use it in your Vue template like so:

<styled-div padd justifyContent="flex-start" ></styled-div>

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

Issue with floating right navigation functionality

Hi there, I'm experiencing a minor issue with the navigation on my website. When I hover over the right side of the nav bar, the drop down menu shifts slightly to the right. All other elements in the nav are positioned absolutely... nav { pa ...

Libraries using the bootstrap slider are revolutionizing the design of all other layouts

Currently, I am utilizing a slider sourced from the following location: https://codepen.io/kravisingh/pen/pLGzgo Here is the complete code for the page: paste.ofcode.org/Dx5NyPRunupjL6GRysUx9g However, upon adding these libraries, the layout of other s ...

Transferring and bringing in components in React without ES6

I'm currently working on a react project and I want to export my ShoppingList class. However, I prefer not to use ES6 as I find it confusing. Here is the code for the ShoppingList class: class ShoppingList extends React.Component { render() { ...

Incorporating Dynamic Events into HTML Generated on the Fly within a Vue.js Component

Currently, I am facing an issue where I am trying to dynamically generate HTML in a Vue.js component. While I have successfully rendered the HTML, I am struggling to connect the events for these dynamically generated elements. To illustrate this problem, I ...

JavaScript/Typescript is throwing an error because it is unable to access the property 'username' of an undefined object

In my project, I am attempting to compile a list of Profile objects and then extract specific elements from each object in the list. To accomplish this, I have defined a public interface named Profile, imported it into my component, and instantiated a new ...

Column Locking with Merged Rows

I have implemented row spanning in jqgrid by following the instructions provided in this answer: Jqgrid - grouping row level data However, I am facing an issue where setting a column with row span to frozen = true causes the overlay to lose the row spanni ...

Enhancing User Experience with CSS

Is there a way to create a link within a div and change the hover color to indicate it's a link? The challenge is that my div contains both an image and text in separate divs. div { :hover { background-color: light cyan; } Currently, when I hov ...

Can someone provide guidance on effectively implementing this JavaScript (TypeScript) Tree Recursion function?

I'm currently grappling with coding a recursive function, specifically one that involves "Tree Recursion". I could really use some guidance to steer me in the right direction. To better explain my dilemma, let's consider a basic example showcasi ...

Creating a delay with jQuery before hiding elements

A script on my website displays a dropdown menu when the element with ID #icon-hamburger is clicked. The menu has a nice fading animation when it appears and disappears: // nav-mobile $('#icon-hamburger, .icon-close').click(function() { if ($ ...

Receive alerts for excessive memory consumption in Node.js

I currently have a Node.js application running on Ubuntu 14 through Amazon EC2. My goal is to receive an email notification once the memory usage surpasses a specific threshold. While I am aware that PM2 offers an API feature that allows for app restarts ...

Guide on integrating external HTML into your Nuxt application using an object in a JavaScript file with an HTTP URL given by the bot constructor

My aim is to integrate a bot created with landbot.io into my nuxt web app using the NUXT.js framework. Provided below is the code from the guide given by landbot. Here is the code to include: <script src="https://static.landbot.io/landbot-widget/landb ...

Center the image within the div by setting its position to absolute

<div class='img-box'> <img /> //position absolute <img /> //position absolute <img /> //position absolute <img /> //position absolute I am struggling to center the images within this div because of their absolute p ...

Tips for incorporating data directly within a D3 bullet chart

Within the provided example, the code is utilizing d3.json to fetch data from a local file called "bullets.json" and passing it as 'data' to a callback function for further action. I am looking to modify this process so that instead of fetching ...

Toggle the visibility of elements (such as a form) with a click of a link - Utilize ajax to

I'm attempting to use jQuery to toggle the visibility of a form. This functionality is triggered by clicking on a specific link... The goal is to hide all links with data-action="edit" and only display the form that follows the clicked link, as there ...

Is there a way I can implement lazy loading of results without having to overhaul my entire Laravel + jQuery application built in the Single Page Application style?

I recently created a web application using the Single Page Application concept, but without utilizing any modern technologies or frameworks. In this application, I have a jQuery page that makes dynamic requests to a localhost - a Laravel instance that comp ...

"Explore the dropdown options on the Twitter Bootstrap menu by hovering your cursor

Is there a way to modify the code so that when hovering over a dropdown menu created with Twitter Bootstrap 3, the menu expands and users are able to click on the expanded links? The HTML code I came up with is as follows: <nav> ...

Multiple Class Changing Effects: Hover, Fade, Toggle

I have a simple yet complex problem that I am trying to solve. I want to create links that fade in upon mouseover and fade out when the mouse moves away. Simultaneously, I want an image to slide in from the left while hovering over the links. I have manage ...

Turn off csrf protection when an internal express route is accessed

I have a simple code snippet that implements csrf protection: import csrf from 'csurf'; const csrfProtection = csrf({ cookie: { httpOnly: true, secure: process.env.NODE_ENV === 'production', }, }); app.use(csrfProtection) ...

Displaying Highcharts Graph in Dual Containers

Could you kindly review this demonstration and provide guidance on how I can display one Highcharts chart in two separate containers? I have attempted both: renderTo: 'container', renderTo: 'container2', and renderTo: 'containe ...

Transform the usual button into a jQuery button that requires a press and hold action

Within my code, there are two buttons in play. One button triggers the burger menu, while the second button adjusts the size of a div. I am looking to transform only the second button into a hold button that activates after a 3-second delay. code: $doc ...