how to protect embedded div style not to be overridden by website style - css

I have div with its own style. I embedded this div on other website.
<div id="scoped-div">
<style>
label {
color: green;
}
</style>
<label> Scoped div </label>
</div>
But I face problem, my div style is overridden by website style. I don't want to use iframe. Except for the use of iframe is there any other way to protect my div style by external style changes?

Your request is exactly what Shadow DOM makes possible:
attach a Shadow DOM to the element you want to protect (here:
#scope-div),
put the HTML code you want to protect in the Shadow DOM,
clone it from a <template> element to get it easy (optional).
That's it!
var div = document.querySelector( "#scoped-div" )
var template = document.querySelector( "template" )
var sh
if ( 'attachShadow' in div )
sh = div.attachShadow( { mode: "closed" } ) //Shadow DOM v1
else
sh = div.createShadowRoot() //Shadow DOM v0 fallback
sh.appendChild( template.content.cloneNode( true ) )
<template>
<style>
label {
color: green;
}
</style>
<label> Scoped div </label>
</template>
<div id="scoped-div">
</div>

There is no way to fully protect your styles. But you can try the following:
Try to specify your elements selectors as specific as possible (e.g. with attributes and IDs)
Use inline styles
Use !important (but be careful with a broad use of importants)

Related

CSS shadow dom : is there alternative to /deep selector?

As far as I know, the /deep selector is deprecated to select shadow dom children. So I'm looking for another solution.
CSS scoping looks to provide solutions for ascending selector, but not for descending one.
Given this dom :
<script>
$('.child').addClass('reached');
</script>
<div id="parent">
#shadow-root
<div class="child"></div>
/shadow-root
</div>
How can I write the selector in the script to reach the .child element ?
Thank you for your help
How can I write the selector in the script to reach the .child element?
To reach an element in the Shadow DOM, you should use the shadowRoot property on the element.
var parent = document.querySelector( '#parent' )
var child = parent.shadowRoot.querySelector( '#child' )
child.classList.add( 'reached' )
Note : the Shadow DOM must have been created in the open mode.
var sh = parent.attachShadow( { mode: 'open' } )
var parent = document.querySelector( '#parent' )
var sh = parent.attachShadow( { mode: 'open' } )
sh.innerHTML = `<style>
div.reached { color: green }
</style>
<div id="child">Child</div>
`
var child = parent.shadowRoot.querySelector( '#child' )
child.classList.add( 'reached' )
<div id="parent">
</div>
Note: ::slotted is needed only if you have elements in the light DOM revealed with <slot>.
Is there alternative to /deep selector?
Short answer is no. Since Shadow DOM is aimed at isolating Shadom DOM from the main page, /deep was kind of an heresy.
A very new proposal, with ::part and ::theme pseudo-elements could give some control back, but it's not to be implemented soon.
Until then the main workaround is to use CSS custom properties.
However the 2 solutions must be implemented by the Web Component designer and cannot be overrided otherwise.

Apply stylesheet to half a page with shadow-dom?

Can I apply an external stylesheet to a specific div/element with shadow-dom or via any other means? I've heard about shadow-dom and I believe it lets you constrain your styles, but that's about all I know.
Specifically, I want half the page to use bootstrap, and the other half to use MUI or something else. This is just to show how my library works nicely with different themes.
I don't want to modify the CSS in anyway to constrain it to a specific element, nor do I want to use iframes.
Yes, you can apply an external stysheet in a Shadow DOM using the #import url CSS rule.
div.attachShadow( { mode: 'open' } )
.innerHTML = `
<style>
#import url( './external-style.css' )
</style>
<!-- other elements -->`
NB: The #import rule must placed at the top of the <style> element.
You can then manipulate the Shadow DOM like a normal DOM:
div.shadowRoot.appendChild( firstSection.cloneNode( true ) )
If your content is already existing in the normal DOM, you can move it with appendChild(), duplicate it with cloneNode() as in the above example), or reveal it with the help of <slot> element:
div1.attachShadow( { mode: 'open' } )
div1.shadowRoot.innerHTML = `
<style>
:host { display: inline ; background: #cfc ; }
::slotted( span ) { color: red ; }
</style>
<slot></slot>`
<div id=div1>
<span>Hello</span> world
</div>
In the last case you'll need to use the ::slotted pseudo-element to change the style of the original DOM, so maybe you'll have to modify already existing stylesheet. The best solution depends on your use case.

apply css class to all instances

Im trying to style some autogenerated html. I built a system that allowed me to overlay bootstrap on this autogen stuff and now I want to do some tweaking of whats there.
the autogen produces stuff like this
<dl>...</dl>
Now I want to apply bootstraps dl-horizontal class to that generated tag. Since its generated, I can't simply class it, I can't ID it, nothing. It has to be purely CSS selectors, which is something I know very little about.
What would a CSS tag that does this look like?
you can use jQuery to add a class to your <dl> tag like this:
$( document ).ready(function() {
$("dl").addClass("dl-horizontal");
});
$( document ).ready(function() {
$("dl").addClass("dl-horizontal");
});
.dl-horizontal {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>
jsFiddle Demo.
There is no option in css to add a class. But you can use children selectors to format if all your elements are the children of the same parent.
For example if your elements are a children of the parent body then:
body > dl
{
color : red;
}
The above code will change the text - color of all the elements that are the children of

Can Reactjs programmatically handle :before?

I somehow have to programmatically set the width of the :before for a div.
<div className="something" style={someStyle}> </div>
How can I define the someStyle so that the width of the :before of .something``div can change accordingly??
Yes, you can programmatically change the value of pseudo-elements like ::before, ::after in react.
Here is a trick.
app.js
const widthVar = 34;
const someStyle = {
"--width": widthVar
}
<div className="something" style={someStyle}> </div>
style.css
.something:before{
width: var(--width),
// remaining code
}
Pseudo elements cannot be styled with inline styles as explained in https://stackoverflow.com/a/14141821/368697. You will have to style the something class name in a stylesheet with the .something:before selector. This is not a limitation of React but rather a design choice for HTML + CSS.
If you need to programmatically change the width of the pseudo :before element, it is probably more appropriate as a regular DOM element rendered by React.
I got insight from #am2505 to use CSS variables as it helped me however, this way avoids inline styling.
HTML
<div className="something"> </div>
CSS
:root {
--width: <yourDefaultValue>
}
.something:before{
width: var(--width),
}
JS
const changeWidth=() => {
let root = document.querySelector(':root');
root.style.setProperty('--width', '<yourNewValue>px');
call the function at the event you want the width to change.
The changeWidth function can be further modified to dynamically work with state using conditional statements.

Set the css property of a class based on its visibility property using CSS only

I have a set of div whose visibility is set to either hidden or visible. Based on this css visibility property i need to add the css property on those div, like
<div class="div-class" style="color:#ff0000; margin: 0px 10px; visibility:hidden;">
[Block of Code]
</div>
Now i need to define the following in style.css file.
.div-class:visible {top:10px;left:50px;}
.div-class:hidden {top:0px;left:0px;}
Is this possible???
yes with css attributre selectors you can do it
try the below css:
.div-class[style*="visible"] {
color: green;
}
.div-class[style*="hidden"] {
color: red;
}
What you are trying to do is not "really" possible.
I mean it's ill thought by design in the first place.
Even Vamsikrishna's solution might not work as expected.
If you set the overflow property to hidden via javascript or inline styles, the .div-class[style*="hidden"] rule will apply since the style attribute will contain the hidden string.
Moreover , setting inline styles on html elements is bad practice itself in most cases.
I suggest you try and learn css principles a little more.
I'd do the following:
HTML
<div class="div-class div-hidden">
[Block of Code]
</div>
CSS
.div-class {color:#ff0000; margin: 0px 10px; top:10px;left:50px;}
.div-hidden {visibility:hidden;}
.div-class.div-hidden {top:0px;left:0px;}
Then you can use javascript to toggle the "div-hidden" class.
You can do something using attrchange - a jQuery plugin ,
like this:
Add "attrchange" script into HTML page like
In Javascrip catch event
var email_ver_input = $("input#email_ver_input.verifyInput");
email_ver_input.attrchange({
trackValues: true,
callback: function (event) {
if (email_ver_input.is(":visible")){
$("#inputcode_wrap").show();
}
}
});

Resources