Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing CSS class definition

Suppose I have this class:

.MyClass{background:red;}

This class applies to several divs. I want to change the color of the background to orange by changing the color defined in MyClass.

Now, I know I could do $('.MyDiv').css('background', 'orange');

But my question is really this: how do I change the CSS class definition so that MyClass elements now have background:orange;? I want to be able to change several CSS color properties from one color to another.

Thanks.

like image 598
frenchie Avatar asked May 17 '12 21:05

frenchie


People also ask

What is a CSS class?

A CSS class is an attribute used to define a group of HTML elements in order to apply unique styling and formatting to those elements with CSS. Let’s look at an example of how CSS classes work. Below, we have a simple HTML page with three headings ( h2 elements) and three paragraphs ( p elements).

How to apply a CSS style to a class within another class?

Want to apply a CSS style to a class within another class? In this tutorial, I'll show you everything you need to know to use CSS classes. To nestle classes or any other selector in CSS, just separate the selector hierarchy with spaces. Example: .parent .child { /* CSS Properties */ }

How to use CSS classes to style page elements?

You can use CSS classes to group HTML elements and then apply custom styles to them. You can make classes and apply them to text, buttons, spans and divs, tables, images, or just about any other page element you can think of. Let’s now take a closer look at how we can use CSS classes to style page elements.

How do you select a class in CSS?

In CSS, a class selector is formatted as a period (.) character followed by the name of the class. It selects all elements with that class attribute so that unique CSS declarations can be applied to those specific elements without affecting other elements on the page.


2 Answers

Here's my answer in case anyone stumbles upon this. Give your elements a new class name that doesn't already exist, then dynamically add a style segment:

var companyColor = 'orange' //define/fetch the varying color here
var style = '<style>.company-background {background-color: ' + companyColor + '; color: white;}</style>';
$('html > head').append($(style));

//give any element that needs this background color the class "company-background"
like image 65
GreenRock Avatar answered Oct 22 '22 22:10

GreenRock


Actually altering your stylesheet is pretty challenging. Much more easily, though, you can switch out your stylesheet for a different one, which may be sufficient for your purposes. See How do I switch my CSS stylesheet using jQuery?.

For actually altering the stylesheet content, How to change/remove CSS classes definitions at runtime? will get you started.

like image 24
chaos Avatar answered Oct 23 '22 00:10

chaos