0

I have a custom.css with these rules:

div#widget {background:red !important;}
div#widget2 {background:#f0f0f0;}
div#widget2:hover {background: rgb(10,20,30);}

These rules could be anywhere in the custom.css file:

Example:

div#widget {background:red !important;}
.mainwrapper {background:blue;}
div#widget2 {background:#f0f0f0;}     
p {font-size:12px;}
div#widget2:hover {background: rgb(10,20,30);}

Now my thought is to add another css-file to overrule existing custom.css rules like this:

div#widget {background:yellow !important;}
div#widget2 {background:#000000 !important;}
div#widget2:hover {background: #ffffff !important;}

Instead of adding a new custom css file with !important-rules I'm thinking... Is there a way to replace current custom.css rules with the new background-colors? Is this possible to achieve (in a secure way) in php?

(Now I'm creating a new css like this)

$fp = fopen( "newcustom.css", 'w');
fwrite($fp, $important_css);
fclose($fp);

UPDATE Clarification. I have a system where users can creates widgets. Widget code is created so the user could easily copy and paste it into his/her website. A reference to custom css is created for the user.

Now I'm updating the system... If I have to add new css file then the user would have to have to copy and paste a new widgetcode for the new css to work. If I could replace current custom.css then it would work "right away".

bestprogrammerintheworld
  • 5,417
  • 7
  • 43
  • 72

3 Answers3

3

Overriding matters the ordering of your stylesheets included. So include your new css file later after the custom.css:

<link rel="stylesheet" type="text/css" href="custom.css" />
<link rel="stylesheet" type="text/css" href="new_file.css" />

So, now the last rule override the first one:

div#widget {background:red;}
div#widget {background:blue;} /* this will work */

Whatsoever, the css rules defined later for the same would work.

If you don't want to change your ordering for css rules, you may define some class name per specific page and then work with that:

div#widget.page3_widget {background:blue;} /* this will work */
div#widget {background:red;}

Furthermore, you may see my another answer to know how css specificity work. Knowing css specificity rules, you may play well with your css.

Community
  • 1
  • 1
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

You can easily add new css to your html by using jQuery.

Like (#div_id').css('{ }');

Arshid KV
  • 9,631
  • 3
  • 35
  • 36
0

Why don't you simply add a Class Name for the particular HTML ELEMENT? And by doing this. Write/overwrite the current CSS RULES like:

div.newWidget {background:red !important;}
hmd
  • 960
  • 2
  • 9
  • 13