Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change css values (like color in whole app) etc

I have one question...

If you want conditional styling: you must use ng-class or ng-style construction.

But...

For example: I'm an admin, and I want to change color of my application with custom color from colorpicker. How can I change some code in css?

For example I have this line in style.css:

body{
  background: #ffffff;
}

(also all tags like a, h1 etc implement some color)

and in controller I change this #ffffff to #000000.

What is the best way to change this color in css, without using ng-class or ng-style on each tag in each controller?

like image 905
brabertaser19 Avatar asked May 18 '15 09:05

brabertaser19


People also ask

How do I change dynamic style in CSS?

color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.

What is dynamic CSS?

This is a collection of methods which give you the ability to query the stylesheets collection in a document, add and remove rules, and dynamically create new sheets.


2 Answers

The best way is generate a file like color.css with all css rules with color, background-color, border-color etc. overridden. But angularjs will not be enough.

color-default.css

body {
    background: #fff;
}

color.css

body {
    background: #f00;
}

Full JS way
Add class on every element you want to override. Create class for every properties like so:

.skin-color { color: {{color}}; }
.skin-background-color { background-color: {{color}}; }
.skin-border-color { border-color: {{color}}; }
etc..

Apply class on your html where you want:

<h1 class="skin-color">My title</h1>
<p>Hello I'm online!</p>
<p class="skin-background-color">No difference!</p>
<p><a href="#">I'm link</a></p>

You can save the color variable in localStorage for example.
Démo: http://codepen.io/anon/pen/jPrabY

like image 123
Bluety Avatar answered Oct 05 '22 23:10

Bluety


You could write the CSS rule in JavaScript and add it to a stylesheet dynamically. A couple of good articles on how to do that are here and here.

var myColor = '#FF00FF';
var stylesheet = /* get stylesheet element */;
stylesheet.insertRule('.dynamic-color { background-color:"' + myColor +'";}',0);

Of course, in a pure Angular way, you would create a directive that wraps the DOM/stylesheet interaction.

like image 28
Tibos Avatar answered Oct 06 '22 00:10

Tibos