Hi @mc
in razor pages? the css will be .sta[b-wjkjgsnjfl] If I create dom in jquery <div class="sta"></div> I can not use this css?
This issue relates the Razor Page CSS isolation. the b-{STRING}
is generated by framework. For the dynamic content, if you use F12 developer tools to check the elements, you can see they are not containing the b-{string}
, so the CSS not working.
Since, we can't directly use JQuery to generate the random string and use it when append the dynamic content. But we can see that the random string in the page is the same when the page is rendered. So, when we append the dynamic content, we can first to get the b-{string}
from the initial existed DOM element, then use it in the new content.
Refer to the following sample code:
Index.cshtml:
<div class="sta">
aaa<br /> aaa<br />
</div>
<input type="button" id="btnadd" value="Add Div" />
<div id="dynamiccontent">
</div>
@section Scripts{
<script>
$(function(){
$("#btnadd").click(function(){
//to get the b-{string}
var attrs = document.getElementById("dynamiccontent").attributes;
var isolation = "";
$.each(attrs, function (i, elem) {
if (elem.name.startsWith("b-")) {
isolation = elem.name;
}
});
$("#dynamiccontent").append("<div "+isolation+" class='sta'>bbb<br/>bbb<br/></div>");
});
});
</script>
}
Index.cshtml.css
.sta {
background-color:aqua;
}
Then, the result as below:
Update:
we can also try to use the ::deep
pseudo-element to add css for the dynamic or child elements.
For example:
::deep .sta, .sta {
background-color: aqua;
}
and
<div class="sta">
aaa<br /> aaa<br />
</div>
<input type="button" id="btnadd" value="Add Div" />
<div id="dynamiccontent">
</div>
@section Scripts{
<script>
$(function(){
$("#btnadd").click(function(){
/var attrs = document.getElementById("dynamiccontent").attributes;
//console.info(attrs);
//$.each(attrs, function (i, elem) {
// if (elem.name.startsWith("b-")) {
// isolation = elem.name;
// }
//});
$("#dynamiccontent").append("<div class='sta'>bbb<br/>bbb<br/></div>");
});
});
</script>
}
The result as below:
More detail information, see ASP.NET Core Blazor CSS isolation(#Child component support).
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion