So basically I have a page that has it\'s own CSS. On my server I have a folder of different CSS style files, so I want to have a \"preview\" window on my page for them. Can
Like Quentin said, you can use descendent selector to limit the scope. Something like less can help a lot. For example, I would like to have "bootstrap.css" applies only to #MyDiv, in "my.less":
#MyDiv {
@import "bootstrap.less";
}
"bootstrap.css" should be renamed (or linked) to "bootstrap.less". Run:
lessc my.less my.css
would add #MyDiv to every selectors in the imported file.
You could use an iframe to load the preview page or dynamically load the CSS into the page. But, if you want the styles to only by applied to the div, you have to prefix your CSS selectors with the id of the div. #div-id #element-inside-div { }
.
The script for loading it in might look something like this:
var cssFile = document.createElement( "link" );
cssFile.rel = "stylesheet";
cssFile.type = "text/css";
cssFIle.href = "file.css";
document.getElementsByTagName( "head" )[0].appendChild( cssFile );
For one of my projects, I needed exactly the same thing, but to be also supported in CSS version 2.
After a long search all over the web, I didn't found anything useful, so I decided to created this functionality using JavaScript that can actually able to apply a whole css to a specific Element in DOM.
Just call the function applyCSSFileToElement, as described below (depended on jQuery library):
function renderCSSForSelector(css, selector) {
return ((css+"")||"").replace(/\n|\t/g, " ")
.replace(/\s+/g, " ")
.replace(/\s*\/\*.*?\*\/\s*/g, " ")
.replace(/(^|\})(.*?)(\{)/g, function($0, $1, $2, $3) {
var collector = [], parts = $2.split(",");
for (var i in parts) {
collector.push(selector + " " + parts[i].replace(/^\s*|\s*$/, ""));
}
return $1 + " " + collector.join(", ") + " " + $3;
});
}
function applyCSSToElement(css, elementSelector) {
$("head").append("<style type=\"text/css\">" + renderCSSForSelector(css, elementSelector) + "</style>");
}
function applyCSSFileToElement(cssUrl, elementSelector, callbackSuccess, callbackError) {
callbackSuccess = callbackSuccess || function(){};
callbackError = callbackError || function(){};
$.ajax({
url: cssUrl,
dataType: "text/css",
success: function(data) {
applyCSSToElement(data, elementSelector);
callbackSuccess();
},
error: function(jqXHR) {
callbackError();
}
})
}
Functions explanations:
Good luck!
CSS applies to entire documents.
If you want to limit the scope, then you need to make use of a descendent selector.
e.g. #id_of_div .the .rest .of .the .selector {}
You have to apply this to every selector, and take into account groups (so it isn't as simple as just prefixing the whole stylesheet and suffixing every }
)
You would also find the stylesheet for the main document applying to your preview.
A frame would probably be the best approach to solving this problem.