Leveraging Vue properties within CSS styling

I am looking to utilize Vue data/prop variables within the <style> tag located at the bottom of my component.

For example, suppose I have a component structured like this:

<template>
  <div class="cl"></div>
</template>
<script>
export default {
  data () {
    return {
      val: '30px'
    }
  } 
..
}
</script>
<style>
.cl p{
  height: 30px;
}
</style>

I want to find a way to incorporate the val data variable into the <style></style> in order to style accordingly.

I understand that using

<div :style="{'height':val}"></div>
allows for styling based on Vue props/variables but it only sets the style for that specific div. I aim to apply a consistent style to all p tags or any other tags inside my div by declaring it as a class.

One approach is defining a class and toggling its activation (true/false) value, such as :

<div :class="{'cl': someBoolVariable}"></div>
. However, what if I require the height to be dynamic, adjusting based on some calculation/value passed from the parent component?

Ideally, I am seeking something along these lines:

<style>
.cl p {
  height: val;
}
</style>

If anyone has suggestions on how to achieve this, or a simple workaround to make it possible, kindly share.

Answer №1

To accomplish this, simply utilize a CSS variable within your primary div element

<template>
  <div class="cl" :style="'--p-height: ' + val"></div>
</template>

<script>
  export default {
    data() {
      return {
        val: '30px'
      } 
    }
  }
</script>

<style>
.cl p {
  height: var(--p-height);
}
</style>

For reference, here is a jsfiddle example

Answer №2

Vue 3 makes styling easier with the v-bind directive for applying styles:

<template>
  <div class="textbox">Styled text</div>
</template>

<script setup lang="ts">
const textColor = '#3478ae'
</script>

<style scoped lang="scss">
.textbox {
  color: v-bind(textColor);
}
</style>

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

Mastering the art of column stacking with CSS on your WordPress website

Looking for a CSS solution to adjust the layout when the screen resolution is lowered. Currently, I have two rows with three columns in each row, containing blurbs. My goal is to make these two rows convert into three rows with two columns each at a cert ...

Press one button to activate another button

I am looking to activate a button's class by clicking on another button. The button I have is: <button class="clear-cart banner-btn">clear cart</button> This button is used for clearing a cart. On the order confirmation page, I click on ...

Guide to iterating within a loop with a variable number of iterations above or below the specified amount in JavaScript

I am currently engaged in a project for a small theater group, and I am facing challenges with getting this loop to execute properly. <% include ../partials/header %> <div class="jumbotron jumbotron-fluid"> <div class="container"> ...

Is it possible to execute a function once an element has finished loading?

I am facing a challenge with running the List_Sandbox functions after a specific each loop. This loop selects checkboxes that trigger a change event, rendering additional checkboxes that need to be selected. The issue arises when the List_Sandbox functio ...

Retrieve information and update state right before component display in React Native

Consider this scenario: I have a modal that displays data from its state, which is an array. The state is set in the componentDidMount() function as recommended in the documentation. My goal is to display updated data every time the modal opens. I was able ...

Issue occurred while executing the fs.rename() function in a loop in Node.js

I'm currently working on a project that involves organizing uploaded files into folders based on their request ID. I am using express-request-id to retrieve this ID. The issue I am facing is that whenever there are multiple files to be moved, the pro ...

Submitting data using various submit buttons in PHP

I am facing an issue with multiple submit buttons in my form, each containing hidden values that are dynamically generated. The problem arises when I can see the correct values in the HTML source code, but upon submitting one button, all other values get s ...

Using JavaScript Regular Expressions to locate all prefixes leading up to a specific character

Consider a scenario where you have a string consisting of terms separated by slashes ('/'), like this: ab/c/def Your goal is to identify all the prefixes of this string up to a slash or the end of the string. For the given example, the expected ...

Using Jquery to handle input data in a form

Using jQuery, I have set up an AJAX function to fetch data from a database in real-time as the user fills out a form with 5 input fields. Currently, my code looks like this: $("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load ...

Troubleshooting: My Bootstrap collapse navbar refuses to cooperate

Hi there! I'm working on creating a responsive navbar with Bootstrap, but I'm having trouble getting the collapse feature to work. Can someone please assist me? Here are the lines of code I have: <nav class="navbar navbar-expand-md navba ...

Vue component fails to trigger upon receiving the 'mouseleave' event

I am currently working on a navbar with dynamic component navigation, where hovering over a navbar-link should display the corresponding component and hiding it when the mouse leaves. Although the components are displayed correctly upon hover, they do not ...

Unable to locate the reverse for 'my_views_name' without any arguments in Django. Bridging server-side code with client-side JavaScript using jQuery

How can I create a button to update a URL after fetching data from the database using jQuery AJAX? This is my code in views.py: def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for i in lists: ...

When modifying an array, the v-for directive causes all styles to be re-rendered

I am facing an issue with my v-for list that displays items from an array. The main problem is that when I make changes to the array, all the components get re-rendered entirely instead of just appending or prepending new elements. This results in a signif ...

When using a variable to fetch data in JSON, an undefined error occurs. However, if a hardcoded index

I am facing an issue while trying to extract and manipulate JSON data from a file for an application I am developing. When looping through the data, I encounter an undefined error that seems to indicate a missing property in the JSON object when accessing ...

continuously refresh choices available for selection

I am looking for a way to dynamically populate the second select option based on the selection made in the first select option. While I know how to achieve this using traditional jQuery and HTML, I was wondering if there is a way to update options_for_sele ...

Automating user login with node.js and passport.js: A step-by-step guide

My login application is built using node.js and passport.js, with the session being maintained using express-session and connect-mongo. I need to ensure that users are redirected to the home page upon accessing the URL, only sending them to the login page ...

JSON file not found by the system

I am currently working on a basic program that consists of 3 files: 1. An HTML file named index.html 2. A JavaScript file named app.js 3. A JSON dataset called dataset.json I am struggling to make the browser recognize the data in my program. This is ...

Show the cell data when the checkbox next to it is selected

I have a specific table setup and I am trying to display the content of the table cell if its corresponding checkbox is checked upon clicking a button. For example: If Row2 is checked, an alert box should display Row2 Below is my code snippet, Java ...

Tips for customizing the color of Menu in material-ui v5

I've been searching for solutions to change the background color of the Menu, but the methods I found are outdated. The use of @mui/styles and makeStyles is now deprecated, as stated in mui.com/styles/basics/#hook-api. I attempted to change the backgr ...

Vue transition not functioning properly when hovering over text for changes

When you hover over the circular region on the website, the text and description in the red box will change. To add a fade animation effect when the text changes, I attempted to use <transition> as per the documentation provided in this link. Unfor ...