How can I encapsulate <style>
inside a <div>
only to that <div>
?
The content inside <div >
will come from database with predefined <style>
and other elements, so I can't add classes to elements and style those elements according to their class
First heading's color should be green while second heading's color should be red
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<style>
h1 {
color: green;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<div >
<style>
h1 {
color: red;
}
</style>
<h1>This is a heading inside div.test</h1>
</div>
</body>
</html>
CodePudding user response:
Just use combined selectors that contains the classes of the parent elements:
h1 {
color: purple;
}
.test1 h1 {
color: red;
}
.test2 h1 {
color: green;
}
<h1>This is a heading</h1>
<div >
<h1>This is a heading inside div .test1</h1>
</div>
<div >
<h1>This is a heading inside div .test2</h1>
</div>
CodePudding user response:
What you can do is either give each h1 specific style names. So for your first header it would be:
h1-1 {
color: red;
}
However, this is very inefficient and not very professional. This is the most clean way of handling this:
.test h1 {
color: red;
}
What you are doing is selecting the parent class with .test
and then selected the child class and apply the color red onto it.
Here is a code snippet to show how it works.
.parent .child {
color: red;
}
<h1>This block is uncolored!</h1>
<div >
<h1 >
This is colored red!
</h1>
</div>
CodePudding user response:
I would go as this: every user content from DB has single ID element that wraps it's content and then is mandatory to be included. That way you can encapsulate any style:
h1 {
color: green;
}
<h1>This is a heading</h1>
<!-- random generated ID wrapper -->
<div id="wrapper-00123ABCFF">
<div >
<style>
#wrapper-00123ABCFF h1 {
color: red;
}
</style>
<h1>This is a heading inside div.test</h1>
</div>
</div>
<div id="wrapper-AFFCC0023">
<div >
<style>
#wrapper-AFFCC0023 h1 {
color: yellow;
}
</style>
<h1>This is a heading inside div.test</h1>
</div>
</div>
If generating styles with CssLess it would be extra ease:
#wrapper-AFFCC0023 {
/* ... User style */
}
otherwise you should use some regex to prefix any top level selectors with this user-specific selector