Search code examples
phphtmlcssinternet-explorerstylesheet

Prepend custom css to generated CSS files


here is my problem :

I am working with WordPress and I have simple buttons shortcode.

The user have the possibility to choose a color for each button they create and also a color when the button is hovered.

I got custom css <style> tag generated for each button, it works fine but there is only one problem, it creates a lot of <style> tag in the page and when using IE9 ( which has a limit of 31 ) the button style doesn't apply.

The css is generated with php with my shortcode function.

I am looking for a way to generate the css into a dynamic css file. If all the <style> are put into a single css file it should works with IE but I don't know how I could do that.

Any help would be appreciated.


Solution

  • You can solve it with jQuery:

    function isIE() {
        return (navigator.userAgent.toLowerCase().indexOf('msie ') != -1) || (!!navigator.userAgent.match(/Trident.*rv[:]*11\./));
    }
    
    $(function() {
        if (isIE()) {
            //merging all the content in your generated styles
            var styles = $("style").text();
            //getting rid of the many unneeded styles
            $("style").remove();
            //Putting back all the styles into your document
            $("head").append("<style>" + styles + "</style>");
        }
    });
    

    The idea is to merge the styles into a single text, remove all the styles and then create a single style tag instead of them. You need this only for IE, so I have added a function with which you can check whether it is Internet Explorer and if so, then merge the styles.