How to style slotted parts from the parent downwards - css

How can I style parts which have been slotted into a web component?
My goal is to create 'functional' components which only renders some parts based on the state that they are in (using Redux). These components are then rendered in a container.
This containers knows which kinds of children it can expect and should style the parts from the children accordingly.
An example is a feed of posts, in which all posts are the same web component which only render some parts.
Then there is a grid feed component and renders these posts in a grid.
Another chronological feed might simple render the posts underneath each other.
In both cases the post itself is not aware in the context that it is in.
I want the container component to be responsible for the layout/styling.
I kinda want the inverse of host-context.
With host-context the post component knowns in which containers it can be in and style themself accordingly. But I would like to keep my post component purely functional without any styling. (and host-context is not well supported)
This snippet shows my attempts to make the title of the post red when it is in a my-grid element. But none of my attempts work.
customElements.define('my-grid', class extends HTMLElement {
constructor() {
super().attachShadow({
mode: 'open'
})
.append(document.getElementById(this.nodeName).content.cloneNode(true));
}
});
customElements.define('my-post', class extends HTMLElement {
constructor() {
super().attachShadow({
mode: 'open'
})
.append(document.getElementById(this.nodeName).content.cloneNode(true));
}
});
<template id="MY-GRID">
<style>
:host {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
grid-auto-rows: minmax(auto, 100px);
}
::slotted(my-post) {
display: contents;
}
/* Attempts at styling the parts withing the slotted posts */
my-post h1,
::slotted(my-post) h1 {
background-color: red;
}
my-post ::part(test),
::slotted(my-post) ::part(test) {
background-color: red;
}
my-post::part(test),
::slotted(my-post)::part(test) {
background-color: red;
}
</style>
<slot></slot>
</template>
<template id="MY-POST">
<h1 part="title">Title</h1>
</template>
<my-grid>
<my-post></my-post>
<my-post></my-post>
<my-post></my-post>
<my-post></my-post>
<my-post></my-post>
</my-grid>

You had multiple issues
Typos: You are mixing title and test for your ::part(x) references
::slotted is a very simple selector, so you can discard all those tries
(per above link) Slotted content remains in lightDOM; so your elements in lightDOM:
<my-grid>
<my-post></my-post>
<my-post></my-post>
<my-post></my-post>
<my-post></my-post>
<my-post></my-post>
</my-grid>
must be styled from its container.... in this case the main document DOM
So all global style required is:
my-post::part(title) {
background: red;
}
You can not do this in <my-grid> because <my-post> is not inside <my-grid> lightDOM
<my-grid> can not style its slotted content (only the 'outer' skin with ::slotted)
I added extra styling, slots and a nested <my-post> element to make things clear
<script>
class GridElements extends HTMLElement {
constructor() { super().attachShadow({mode: 'open'})
.append(document.getElementById(this.nodeName).content.cloneNode(true)) }}
customElements.define('my-grid', class extends GridElements {});
customElements.define('my-post', class extends GridElements {});
</script>
<template id="MY-GRID">
<style>
:host{display:grid;grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)) }
::slotted(my-post) { background: green }
</style>
<slot></slot>
</template>
<style id="GLOBAL_STYLE!!!">
body { font: 14px Arial; color: blue }
my-post::part(title) { background: red }
my-grid > my-post::part(title) { color: gold }
my-post > my-post::part(title) { background:lightcoral }
</style>
<template id="MY-POST">
<h1 part="title"><slot name="title">[Title]</slot></h1>
<slot>[post body]</slot>
</template>
<my-grid>
<my-post><span slot="title">One</span></my-post>
<my-post>Two</my-post>
<my-post></my-post>
<my-post>
<my-post><span slot="title">SUB</span></my-post>
</my-post>
</my-grid>
::part Styling declared from my-grid
I added a my-post to the my-grid lightDOM:
See: https://jsfiddle.net/WebComponents/75xgt3y2/
So if you still want to declare the content in the main DOM, but style from my-grid, you have to move elements from the main DOM to my-grid lightDOM:
connectedCallback(){
this.shadowRoot.append(...this.children);
}
Update #1
Also see exportparts for crossing multiple shadowDOM boundaries:
https://meowni.ca/posts/part-theme-explainer/
https://caniuse.com/mdn-html_global_attributes_exportparts
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/exportparts (jan 2021 - no documentation page yet)

Related

set body of web component from attribuate

I've built a web component and I need to set the body of the component when I construct it.
My web component is:
import {html, PolymerElement} from '#polymer/polymer/polymer-element.js';
class TextBlock extends PolymerElement {
static get template() {
var body;
return html`
{body}
`;
}
}
window.customElements.define('text-block', TextBlock)
The page that contains the component is dynamically generated. What I want to do is insert a text-block element into the page as:
<body>
<text-block>
<H1>Title of TextBlock</H1>
</text-block>
</body>
My problem is that I don't understand how to get the web component to take the content between the text-block start/end tags and return it from the call to template()
Whilst not shown, I'm using a webcomponent as I need to style the text using shadow dom.
Don't use Polymer for new Web Components; Google deprecated it years ago.
See: https://polymer-library.polymer-project.org/
Google can't even keep that page up to date; they renamed Lit-Element/html to just Lit.
See: https://lit.dev
Or its 60+ alternatives: https://webcomponents.dev/blog/all-the-ways-to-make-a-web-component/
You can write Vanilla JavaScript Web Components without the soup-starter Lit
Here is a more extended example to cover your next questions:
<style> /* GLOBAL CSS */
text-block { /* inheritable styles trickle down into shadowDOM */
font: 20px Arial;
color: green;
}
div[slot] { /* lightDOM styles are REFLECTED to <slot> in shadowDOM */
width: 200px;
border: 2px solid green;
}
</style>
<text-block prefix="Hello!">
<!-- lightDOM, hidden when shadowDOM is used, then REFLECTED to <slot> -->
<div slot="username">Brett</div>
</text-block>
<text-block prefix="Hi,">
<!-- lightDOM, hidden when shadowDOM is used, then REFLECTED to <slot> -->
<div slot="username">Danny</div>
</text-block>
<template id="TEXT-BLOCK">
<style> /* styling shadowDOM */
div { /* styles do NOT style content inside <slot>, as <slot> are REFLECTED content */
padding: 1em;
background:gold;
}
::slotted(*) { /* slotted can only style the lightDOM 'skin' */
background: lightgreen;
}
</style>
<div>
<slot name="username"></slot>
</div>
</template>
<script>
customElements.define('text-block', class extends HTMLElement {
constructor() {
// see mum! You can use code *before* super() The documentation is wrong
let colors = ["blue","red"];
let template = id => document.getElementById(id).content.cloneNode(true);
super().attachShadow({mode: 'open'})
.append(template(this.nodeName)); // get template TEXT-BLOCK
this.onclick = (evt) => this.style.color = (colors=colors.reverse())[0];
}
connectedCallback(){
this.shadowRoot.querySelector("div").prepend( this.getAttribute("prefix") );
}
});
</script>
For (very) long answer on slots see: ::slotted CSS selector for nested children in shadowDOM slot

How styling works over components in angular?

Question is not clear but I'll break it down. In angular we can write isolated css for styling. It works pretty well for native html elements. But unlike react, angular wrap our html with custom elements like <app-card>...</app-card>. When I write css for those wrapper elements, it doesn't work .
If I have a post list like
<div class="post-list">
<app-card [post]="post" *ngFor="let post of posts"></app-card>
</div>
If I write css to apply some vertical gap between app-card components in PostListComponent. Well nothing happens.
.post-list app-card:not(:last-child) {
margin-bottom: 2rem;
}
How can I make it work? Or with angular logic, how can I apply vertical gap between angular components
Just add display: block; on your app-card component & it will work as expected.
.post-list app-card {
display: block;
}
.post-list app-card:not(:last-child) {
margin-bottom: 2rem;
}
<div class="post-list">
<app-card>Card 1</app-card>
<app-card>Card 2</app-card>
<app-card>Card 3</app-card>
</div>
You can define encapsulation: ViewEncapsulation.None in your Component like this:
#Component({
selector: 'foo',
template: './foo.component.html',
styleUrls: ['./foo.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class FooComponent { }
Which will treat your .css as the same if you were putting it in the global scope.
To be more accurate, it won't append .fooComponent to each css rule in foo.component.scss.
You can make the iteration in div tag then add your class
<div class="post-list">
<div class="post" *ngFor="let post of posts">
<app-card [post]="post"></app-card>
</div>
</div>
And in your css
.post-list .post:not(:last-child) {
margin-bottom: 2rem;
}
There is no reason it shouldn't work. Just tried to put in some of your code here. https://stackblitz.com/edit/angular-scss-demo-icqrye
app.component.html
<div class="post-list">
<app-new *ngFor="let item of [1,2,3,4]"></app-new>
</div>
styles.scss
.post-list app-new:not(:last-child) p {
margin-top: 2rem;
color: green;
}
And it works perfectly. Are you looking for something else?
And if you want to add the style (margins) to the component directly, you will first need to set the display of the component to block/flex as per requirement.
.post-list app-new:not(:last-child) {
display: flex;
}

How do I style the last slotted element in a web component

I have a web component that has a template which looks like this...
<template>
<div class="jrg-app-header">
<slot name="jrg-app-header-1"></slot>
<slot name="jrg-app-header-2"></slot>
<slot name="jrg-app-header-3"></slot>
</div>
</template>
I am basically trying to set the contents of the last slot to have flex:1; in style. Is there a CSS query that will do this? I tried something list
::slotted(*):last-child{
flex:1;
}
But it did not work. How do I style the last slotted object?
For long answer on ::slotted see: ::slotted CSS selector for nested children in shadowDOM slot
From the docs: https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted
::slotted( <compound-selector-list> )
The pseudo selector goes inside the brackets: ::slotted(*:last-child)
Note: :slotted(...) takes a simple selector
See (very) long read: ::slotted CSS selector for nested children in shadowDOM slot
customElements.define('my-table', class extends HTMLElement {
constructor() {
let template = (name) => document.getElementById(name)
.content.cloneNode(true);
super()
.attachShadow({ mode: 'open' })
.append( template(this.nodeName) );
}
})
<template id="MY-TABLE">
<style>
:host { display: flex; padding:1em }
::slotted(*:first-child) { background: green }
::slotted(*:last-child) { background: yellow; flex:1 }
::slotted(*:first-of-type) { border: 2px solid red }
::slotted(*:last-of-type) { border: 2px dashed red }
</style>
<slot name="column"></slot>
</template>
<my-table>
<div slot="column">Alpha</div>
<div slot="column">Bravo</div>
<div slot="column">Charlie</div>
</my-table>
<my-table>
<div slot="column">Delta</div>
<div slot="column">Echo</div>
</my-table>
JSFiddle playground:
https://jsfiddle.net/WebComponents/108ey7b2/
More SLOT related answers can be found with StackOverflow Search: Custom Elements SLOTs

CSS is not fully applying on a shadow DOM using <slot>

I have the following simple component:
Usage:
<style>
my-element {
--my-bg: green;
--my-text: red;
}
</style>
<my-element myStyling>
<p>Test</p>
</my-element>
Component:
const template = document.createElement('template');
template.innerHTML = `
<style>
:host([myStyling]), :host([myStyling]) {
background-color: var(--my-bg);
color: var(--my-text);
}
</style>
<slot></slot>
Static
`;
class MyElement extends HTMLElement {
constructor() {
super();
// Attach a shadow root to the element.
let shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
window.customElements.define('my-element', MyElement);
The code outputs the following result:
Why the color: green applies on the static text and the shadow DOM both, while the background color style applies only on the static text?
Default value for CCS property color is inherit.
Default style for CSS property background-color is transparent (won't inherit from its parent element).
Default custom element display property is inline (= phrasing content) and therefore won't settle background properties to its children.
In your code, the "Test" text is in a <p> element, that won't inherit from the :host background color, but will be transparent and therefore will display the background color of the main page, which is white.
See the live example below for a complete use case.
const template = document.createElement('template')
template.innerHTML = `
<style>
:host {
background-color: var(--my-bg);
color: var(--my-text);
}
</style>
<slot></slot>
<hr>
Text in Shadow DOM root
<p>Text in Paragraph in Shadow DOM <span>and child Span</span></p>
<span>Text in Span in Shadow DOM <p>and child Paragraph</p></span>`
class MyElement extends HTMLElement {
constructor() {
super()
this.attachShadow({mode: 'open'})
.appendChild(template.content.cloneNode(true))
}
}
window.customElements.define('my-element', MyElement)
body {
background-color: lightblue;
}
my-element {
--my-bg: green;
--my-text: red;
}
<my-element myStyling>
Text in Light DOM root
<p>Text in Paragraph in Light DOM <span>and Child Span</span></p>
<span>Text in Span in Light DOM <p>and child Paragraph</p></span>
</my-element>
If you want the background-color to be applied to all the child elements inside the Shadow DOM, you must apply the css rule to the * selector too:
:host, * {
background-color: ...
}
If you want the background-color to be applied to all the light DOM elements inserted with <slot>, you must add a ::slotted(*) pseudo-element rule:
:host, *, ::slotted(*) {
background-color: ...
}
Alternate approach
If you want the background-color to be applied between the different parts of text, don't forger to define the display property as inline-block or block (= flux content).
As a consequence all children will display the root block background-color.
Here is the complete <style> definition for the Shadow DOM:
:host {
display: inline-block ;
color: var(--my-text);
background-color: var(--my-bg);
}

I have a plunker. When I define my css globally, it works. When I define my css in my component, it fails. What's going on?

With reference to this plunker:
https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview
I have the same css specified in the styles.css file, and in the src/app.ts file.
If I comment in the css in styles.css and comment out the css in src/app.ts, it works.
styles.css:
/* If these are commented in, and the ones in src/app.ts are
* commented out, the three items are spaced appropriately. */
/***
md-toolbar-row {
justify-content: space-between;
}
md-toolbar {
justify-content: space-between;
}
***/
If I comment out the css in styles.css and comment in the css in src/app.ts, it fails.
src/app.ts:
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<md-toolbar color="primary">
<span><md-icon>mood</md-icon></span>
<span>Yay, Material in Angular 2!</span>
<button md-icon-button>
<md-icon>more_vert</md-icon>
</button>
</md-toolbar>
</div>
`,
// If these are commented in, and the ones in style.css are
// commented out, the three items are scrunched together.
/***/
styles: [
`md-toolbar-row {
justify-content: space-between;
}`,
`md-toolbar {
justify-content: space-between;
}`
]
/***/
})
export class App {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
}
I'm having trouble visualizing the difference between defining the css for the whole application, and for the specific component. Can someone tell me what's going on?
=================================
#bryan60 and #Steveland83 seem to indicate that the problem lies somewhere in the view encapsulation. And upon further investigation, it does in a sense.
If you look at the code below, you will see that the styles for md-toolbar and md-toolbar-row have an attribute attached. But the html for md-toolbar and md-toolbar-row does not match. Only md-toolbar has the attribute attached. md-toolbar-row doesn't. I have marked the relevant four lines with >>>>>.
So that's the problem but:
1. Do I report it to the material design people as an error?
2. Is there some workaround I can use today?
<html>
<head>
:
<script src="config.js"></script>
<script>
System.import('app')
.catch(console.error.bind(console));
</script>
<link href="https://rawgit.com/angular/material2-builds/master/prebuilt-themes/indigo-pink.css" rel="stylesheet">
<style>
>>>>> md-toolbar-row[_ngcontent-c0] {
justify-content: space-between;
}
</style>
<style>
>>>>> md-toolbar[_ngcontent-c0] {
justify-content: space-between;
}
</style>
<style>
.mat-toolbar {
display: flex;
: :
.mat-mini-fab,
.mat-raised-button {
outline: solid 1px
}
}
</style>
</head>
<body class="mat-app-background">
<my-app _nghost-c0="" ng-version="4.4.0-RC.0">
<div _ngcontent-c0="">
<h2 _ngcontent-c0="">Hello Angular! v4.4.0-RC.0</h2>
>>>>> <md-toolbar _ngcontent-c0="" class="mat-toolbar mat-primary" color="primary" role="toolbar" ng-reflect-color="primary">
<div class="mat-toolbar-layout">
>>>>> <md-toolbar-row class="mat-toolbar-row">
<span _ngcontent-c0=""><md-icon _ngcontent-c0="" class="mat-icon material-icons" role="img" aria-hidden="true">mood</md-icon></span>
<span _ngcontent-c0="">Yay, Material in Angular 2!</span>
<button _ngcontent-c0="" class="mat-icon-button" md-icon-button=""><span class="mat-button-wrapper">
<md-icon _ngcontent-c0="" class="mat-icon material-icons" role="img" aria-hidden="true">more_vert</md-icon>
</span>
<div class="mat-button-ripple mat-ripple mat-button-ripple-round" md-ripple="" ng-reflect-trigger="[object HTMLButtonElement]" ng-reflect-centered="true" ng-reflect-disabled="false"></div>
<div class="mat-button-focus-overlay"></div>
</button>
</md-toolbar-row>
</div>
</md-toolbar>
</div>
</my-app>
</body>
</html>
One of the Angular features is View Encapsulation which basically means that you can define styles scoped only to a specific component without affecting any other components.
By default styles are scoped only for the component they are referenced in, but you can choose to override that to make them available globally by setting your components encapsulation to None.
E.g.
import { Component, ViewEncapsulation } from '#angular/core';
#Component({
selector: 'component-that-shares-styles',
templateUrl: './component-that-shares-styles.component.html',
styleUrls: ['./component-that-shares-styles.component.scss'],
encapsulation: ViewEncapsulation.None // <-- Set encapsulation here
})
*Note that you will need to import ViewEncapsulation from #angular/core
Okay, with help from #Steveland83 and #bryon60, I came to a definite answer. The Material Design people are aware of this problem. They have made a writeup.
https://github.com/angular/material2/blob/master/guides/customizing-component-styles.md
Here's their summary:
Styling other components
If your component has view encapsulation turned on (default), your component styles will only
affect the top level children in your template. HTML elements belonging to child components cannot
be targeted by your component styles unless you do one of the following:
Add the overriding style to you global stylesheet. Scope the selectors so that it only affects
the specific elements you need it to.
Turn view encapsulation off on your component. If you do this, be sure to scope your styles
appropriately, or else you may end up incidentally targeting other components elswhere in your
application.
Use a deprecated shadow-piercing descendant combinator to force styles to apply to all the child
elements. Read more about this deprecated solution in the
Angular documentation.
I don't want to use global css, or a deprecated solution. I guess I will style with classes, and not elements. If someone has a better idea, tell me!

Resources