Reputation: 115
Is there a way to change an existing css class definition on a part - fragment of an html document while keeping the original class definition on the rest of the document? I'm not interested to solutions adding additional css classes to differentiate the styles.
For example in the following page (jsbin demo here) I want to redefine the color of the .someClass css class to green on the text of the first paragraph and to red to the text of the second paragraph while use the default class definition on the third paragraph. Tried using the inline css with scoped attribute but it fails - it seems it's not meant for class definitions, the last someClass definition (red color) overrides all previous definitions.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style scoped>
.someClass { color: blue}
</style>
</head>
<body>
<div id="first" >
<style scoped>
.someClass { color: green}
</style>
<p class="someClass">First paragraph</p>
</div>
<div id="second" >
<style scoped>
.someClass { color: red}
</style>
<p class="someClass">Second paragraph</p>
</div>
<div id="third" >
<p class="someClass">Third paragraph</p>
</div>
</body>
</html>
Thanks in advance
Upvotes: 0
Views: 731
Reputation: 722
There is a live Demo at the end of the page
https://css-tricks.com/saving-the-day-with-scoped-css/
Scoped styling seems to suffer cross browser support, http://www.w3schools.com/tags/att_style_scoped.asp however the jQuery example, gives a work around
Upvotes: 1
Reputation: 5838
I think that your best approach would be to use the nth-of-type
selector. Thus you don't add extra css classes and it would work and it is totally supported by all actual browsers.
.someClass { color: blue}
div:nth-of-type(1) p { color: green; }
div:nth-of-type(2) p { color: red; }
<div id="first" >
<p class="someClass">First paragraph</p>
</div>
<div id="second" >
<p class="someClass">Second paragraph</p>
</div>
<div id="third" >
<p class="someClass">Third paragraph</p>
</div>
Upvotes: 0