Inject CSS values dynamically

I am currently working on dynamically setting the color of a div.

To provide some context, let's examine the following:

<!doctype html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="shape" id="shape1"></div>
    <div class="shape" id="shape2"></div>
    <div class="shape" id="shape3"></div>
</body>
</html>

Here is the CSS code I have implemented:

.shape {
  display: inline-block;
  width: 200px;
  height: 200px;
  background: #dfd;
  margin: 20px;
}

I am exploring if it's feasible to use class="shape-fdd" in the HTML to display a light red color, and using class="shape-dfd" for a light green color.

I have briefly researched LESS, but I'm uncertain if it supports this functionality.

I prefer not to rely on jQuery for a solution. Instead, I am looking for options within CSS or utilizing LESS or SASS if applicable.

Any assistance or guidance would be greatly appreciated.

Answer №1

To create a dynamic effect using jquery and two different classes, follow this code snippet:

HTML

<!doctype html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="shape-dfd" id="shape1"></div>
    <div class="shape-dfd" id="shape2"></div>
    <div class="shape-dfd" id="shape3"></div>
    <input type="button" id="classDfd" value="Add dfd class" />
    <input type="button" id="classFdd" value="Add fdd class" />
</body>
</html>

Style

.shape-dfd {
  display: inline-block;
  width: 200px;
  height: 200px;
  background: #dfd;
  margin: 20px;
}
.shape-fdd {
  display: inline-block;
  width: 200px;
  height: 200px;
  background: #fdd;
  margin: 20px;
}
</style>

Jquery

<script>
$(document).ready(function () {

   $("#classDfd").click(function(){

       $("div[id^='shape']").removeClass("shape-fdd");
       $("div[id^='shape']").addClass("shape-dfd");
   });

   $("#classFdd").click(function(){

       $("div[id^='shape']").removeClass("shape-dfd");
       $("div[id^='shape']").addClass("shape-fdd");
   });
});
</script>

Answer №2

[Updated] now that my answer has been approved: I would like to emphasize for future readers that the following method may not work currently: it is not yet supported in css3 (only functional for the content attribute at the moment) :)

Just a quick informational note. Although not currently supported in css3 (only implemented for the content attribute), it might be possible soon:

<!doctype html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="shape" id="shape1" data-color="#fdd"></div>
    <div class="shape" id="shape2" data-color="#fdd"></div>
    <div class="shape" id="shape3" data-color="#fdd"></div>
</body>
</html>


.shape {
  display: inline-block;
  width: 200px;
  height: 200px;
  background: attr(data-color);
  margin: 20px;
}

You can find more information on CSS - Add Color with a data attribute - attr(data-color color)

Answer №3

If you want to add a new style to your HTML elements, simply create a new class in your CSS file and then apply it in your HTML code.

.newClass {
    background: #dfd;
}

After defining the .newClass, you can use it by adding class="shape newClass" to apply the background color defined in the .newClass.

Check out the demo on JsFiddle to see it in action.

Answer №4

If you're looking to dynamically set colors using javascript or jQuery, here's a possible approach. You can define the colors in data-attributes and then specify them in your CSS, or use different classes based on the dynamic requirements.

For example:

[data-color="blue"] {
  background-color: deepskyblue !important;
}

[data-color="red"] {
  background-color: tomato !important;
}

Your HTML would then look like this:

<div class="shape" data-color="blue"></div>
<div class="shape" data-color="red"></div>

Check out the demo on jsfiddle

EDIT If you want to use a mixin or extend in SCSS (or check syntax for LESS), you can create a base class and then extend it with specific colors like so:

.shape {
    background-color: aqua;
    display: inline-block;
    height: 100px;
    width: 100px;
}

.shape-blue {
    @extend .shape;
    background-color: deepskyblue;
}

.shape-red {
    @extend .shape;
    background-color: tomato;
}

See the updated demo on jsfiddle

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

The text element does not line up with the icons

As I'm working on creating my first account page header, I've run into an issue with some of the icons not aligning perfectly with the text. While advanced developers may find this task simple, as a beginner, I could really use some advice on how ...

Adjusting the dimensions of the "overflow avatar" to be consistent with the other avatars displayed in AvatarGroup

When setting the max prop of the AvatarGroup, the additional avatar does not match the height of the other avatars. <AvatarGroup max={3}> <Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" sx={{ width: 24, height: 24 ...

What is the process to create a sticky Material UI grid element?

Currently, I am in the process of developing the front-end for a shopping cart. To organize the content, I have split the container into two columns using Grid container and Grid item. In each column, various components are placed - the left side containin ...

Storing a photo taken with a camera to a local directory on the computer

Currently, I am utilizing HTML5 inputs to capture a picture from the camera by using the code below: <input id="cameraInput" type="file" accept="image/*;capture=camera"></input> Subsequently, I am obtaining the image in blob format and manip ...

Adjustable width columns in Flexbox design

I need assistance with creating a responsive three-column grid layout using Flex in CSS. I have achieved a fairly responsive design by following the CSS provided in the fiddle link below. However, I am facing an issue where the second column (the blue one) ...

Tips for choosing nested elements with basic CSS selectors like nth-of-type or nth-child for Selenium

Is there a way to select the paragraph tag for B (or C) by utilizing nth-child or nth-of-type in Selenium WebDriver? <tr> <td> <p class="myClass">A</p> </td> </tr> <tr> <td> <p ...

Looking for a Javascript tool to select provinces graphically?

Looking for a graphic province selector similar to the one found on this website: . If anyone is aware of something like this, especially in the form of a jQuery plugin, that would be fantastic. Thank you. ...

Move the text to the following line if a horizontal scroll bar is visible using JavaScript/JQuery and CSS styling

I have a section with multiple div elements...how can I ensure that when there is horizontal scrolling in the section, the hidden divs shift to the next line? HTML <section id="a"> <div class="num"> <div class="num"> <div class="num" ...

Developing components through JavaScript

I am attempting to use JavaScript to create an element in my HTML using createElement, but there seems to be an issue in my code. HTML <button class="test_button">I am a test</button> <div class="test"></div> ...

How to dynamically change video source and play local video with Phonegap using JavaScript

I am encountering an issue when trying to play (.play()) a video tag from JavaScript code using Phonegap and JQueryMobile. This page is for my video player. <div data-role="page" id="page-reproduccion" data-theme="b"> <div data-role="content"&g ...

Efficiently adjusting the height of a sticky sidebar

I am currently implementing a Bootstrap grid with two divs in a row. I need my reply-container to be fixed (sticky). However, when setting position: fixed; it is affecting the element's width by adding some additional width. With position: sticky, set ...

When you hover over the button, a picture will appear

This is an example code snippet from W3Schools. It showcases an animated button that reveals a small arrow next to the text when hovered over. The specific line of code responsible for this effect is .button span:after {content: '\00bb'. How ...

Steps for creating a jQuery function that responds to changes in a text box value

Currently, I have a text box containing certain values and a submit button alongside a slider. When I click the submit button, the slider changes. However, I would like to achieve the functionality where instead of clicking the submit button, changing the ...

Transfer file content by dragging and dropping it onto a TextArea when an anchor tag is dropped

Within my application, there are 2 textareas with corresponding code implementing "dragover" and "drop" listeners for each one: // for dragover handleDragOver : function (evt) { var self = this; evt.preventDefault(); console.log ( ...

The overlay of the background image is excessively oversized

After implementing the following CSS to showcase a background image: height: 90%; /* or any other value, corresponding with the image you want 'watermarked' */ width: 90%; /* as above */ background-image: url('<?php echo "study/".$_SESS ...

What impact does the use of CSS in emails have on various email clients and reading formats?

As I delve into customizing my very first (woocommerce) email template, I am considering the option of concealing data using CSS display: none. However, a few questions arise regarding the compatibility and support of CSS and display: none: Do all email ...

Learn the easy steps to position an image to the right using FreeMarker

I'm attempting to align the final image on the right side of the page in order to achieve a symmetrical look. The code I have been using in FTL is as follows, but it consistently ends up next to the middle section: <table class="h ...

The requested resource lacks the 'Access-Control-Allow-Origin' header in a basic HTML form

Can someone help me understand why I keep encountering this error in my basic HTML form? I am attempting to display XML data on my website to showcase news stories, but unfortunately, I keep getting stuck with this persistent error. Any assistance would ...

Is there a way to alter a form element based on the selected image?

Below is a code snippet that allows the price in the 'price' div to change based on user selection. <script type="text/javascript"> function showprice(e){ document.getElementById("price").innerHTML = e.getAttribute(&apo ...

Mastering the art of manipulating Div elements using CSS for the optimal Print View experience

I have a table with several columns and 1000 rows. When I print the page, it breaks the rows onto different pages, showing the remaining rows on subsequent pages. I want to display the complete record in one go. Below is a sample code with only one row in ...