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

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.

Related

Using adjacent sibling CSS combinator (+) with HgClass and dynamic value

I'm just trying to figure out if this is possible or if I need to rethink the way I'm going about things.
Here's a very simple idea of where I'm at
My main list will be constantly having items added and removed by other processes. I use NgFor to generate my items and I'm using the adjacent sibling combinator in my style sheet (+) to add margin-top to all but the first item, then ngClass to apply the class itself.All god so far...
Now I want the value of margin-top to also be dynamic and linked to value coming in from another service.
So my question is just, can anyone give me a way of using the adjacent sibling selector and a dynamic value for the style it applies?
Since rendered CSS won't do variables cross browser yet, one option would be a small script adding a style like this
window.addEventListener('load', function() {
loadStyle(20);
setTimeout(function() { loadStyle(40); }, 1000);
setTimeout(function() { loadStyle(60); }, 2000);
})
function loadStyle(margin) {
var node = document.querySelector('my-app style') || document.createElement("style");
var css = ".my-item+.my-item{margin-top: "+margin+"px;}"
node.type = 'text/css';
if (node.styleSheet){
node.styleSheet.cssText = css;
} else {
node.appendChild(document.createTextNode(css));
}
document.querySelector('my-app').appendChild(node);
}
.my-item{
background-color: red;
}
.my-item+.my-item{
margin-top: 20px;
}
<my-app>
<div class='my-item'>A</div>
<div class='my-item'>B</div>
<div class='my-item'>C</div>
</my-app>
You can use style:
<div *ngFor="let user of userList" [ngClass]="'my-item'" [style.margin]="marginValue">{{user}}</div>
marginValue = '0 0 0 9px';

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

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)

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.

Applying style to a parent block depending on the child's state

With the following block structure:
<div class="container">
<div class="title"></div>
<div class="subject"></div>
</div>
is it possible to hide (display:none) a .container if it's child .subject is empty?
Thanks!
well... you could try to fake it... make title position: absolute and for container set overflow: hidden; container itself will only be visible if you put something into .subject tag. Like this:
jsfiddle example
I believe you'll have to use javascript to do this. In jQuery:
$(".container").each( function() {
if ( $(this).children('.subject').html() == '' ) {
$(this).hide();
}
} );
Example at: http://jsfiddle.net/m5jjs/
Not currently possible in pure CSS in any browser I know of.
There is a jQuery plugin cssParentSelector polyfill for the upcoming parent selector in CSS Selectors Level 4 if you already have a jQuery dependency in the project.
:empty psuedo class can be used if element has no node but you have. Need JS though.
$(".container *") {
if($.trim($(this).html()).length == 0 && $.trim($(this).text()).length == 0 ) {
$(".container").css({ "display" : "none" });
}
});

Is there a CSS "haschildren" selector? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a CSS parent selector?
Is there a css selector I can use only if a child element exists?
Consider:
<div> <ul> <li></li> </ul> </div>
I would like to apply display:none to div only if it doesn't have at least one child <li> element.
Any selector I can use do this?
Sort of, with :empty but it's limited.
Example: http://jsfiddle.net/Ky4dA/3/
Even text nodes will cause the parent to not be deemed empty, so a UL inside the DIV would keep the DIV from being matched.
<h1>Original</h1>
<div><ul><li>An item</li></ul></div>
<h1>No Children - Match</h1>
<div></div>
<h1>Has a Child - No Match</h1>
<div><ul></ul></div>
<h1>Has Text - No Match</h1>
<div>text</div>
DIV {
background-color: red;
height: 20px;
}
DIV:empty {
background-color: green;
}
Reference: http://www.w3.org/TR/selectors/#empty-pseudo
If you go the script route:
// pure JS solution
​var divs = document.getElementsByTagName("div");
for( var i = 0; i < divs.length; i++ ){
if( divs[i].childNodes.length == 0 ){ // or whatever condition makes sense
divs[i].style.display = "none";
}
}​
Of course, jQuery makes a task like this easier, but this one task isn't sufficient justification to include a whole libary.
Nope, unfortunately that's not possible with CSS selectors.
CSS does not (yet) have any parent rules unfortunately, the only way around it if you must apply it only parents that contain a specific child is with the Javascript, or more easily with a library of javascript called jQuery.
Javascript can be written in a similair way to CSS in someways, for your example we would do something like this at the bottom of our HTML page:
<script type="text/javascript">
$('div:has(ul li)').css("color","red");
</script>
(For this you would need to include the jQuery library in your document, simply by putting the following in your <head></head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
If you use jquery, you can try out this function
jQuery.fn.not_exists = function(){
return this.length <= 0;
}
if ($("div#ID > li").not_exists()) {
// Do something
}
There is another option
$('div ul').each(function(x,r) {
if ($(r).find('li').length < 1){
$(r).css('display','block'); // set display none
}
})

Resources