Currently, I am facing an issue with a web application that I am developing. On the left side of the page, there is an editable area, and on the right side, there is a live preview. The live preview area contains an HTML file with specific fields that can be manipulated using the edit area. The problem arises because users can input any HTML and CSS code they want, which sometimes causes their styles to affect the entire page. For instance, if a user sets a background color to red, it might turn the whole page red.
To tackle this issue, I have come up with a solution that involves wrapping the user's styles in a parent class and applying that class to the preview area. This prevents the user's styles from affecting my design. I was thinking of using LESS and jQuery to achieve this, similar to the following pseudo code:
//pseudo code
less.Compile(".ParentClass { " + $("style").html() + "}");
Despite considering this approach, I have been unable to find any LESS libraries that allow me to implement it. Does anyone know of a method through which I can add a CSS parent class to all elements in a style tag?
For example:
<div id="Preview">
<style>
div { background: red; }
</style>
<div>I'm red</div>
</div>
Would need to become:
<div id="Preview">
<style>
#Preview div { background: red; }
</style>
<div>I'm red</div>
</div>
Edit: While it is ideal for styles to be placed in the head section of a document, the HTML documents being handled will ultimately be sent as emails. Email client support for CSS styling is unreliable at best, so placing styles in the body is sometimes necessary. It's frustrating, but I have to adapt to accommodate my target audience.