« Previous 1 2 3 4 5
Modularize websites with Web Components
Web Perfect
Breakthroughs
Listing 6 shows how to format Web Components with stylesheet information from outside the shadow DOM. Elements in the shadow DOM take formatting data, as usual, from the browser's standard stylesheet or from the <Body>
element (e.g., font-family
in line 2). The shadow root can be formatted with the tag name (lines 8-16). However, rather than inheriting any format specifications, it only configures the rectangular area in which the browser renders the Web Components.
Listing 6
CSS for Web Components
01 body { 02 font-family: sans-serif; 03 width:80%; 04 max-width:960px; 05 margin:auto; 06 } 07 08 anot-list { 09 position:fixed; 10 right: 7%; 11 width: 18%; 12 margin-top: 2em; 13 padding: 2em; 14 border-radius: 0.5em; 15 border:1px solid #aaa; 16 } 17 18 article { 19 margin: auto; 20 float:left; 21 margin-left: 20%; 22 margin-right: 30%; 23 } 24 25 li { 26 --anot-item-bg: #ff6699; 27 }
The inner workings of the shadow DOM can otherwise only be formatted by CSS hooks. The specification
background-color: var(--anot-item-bg, #f3f315);
from line 7 of Listing 5 declares a hook for the background color of the list elements. It sets the six-digit RGB value behind the hash mark to neon yellow by default. Line 26 of Listing 6 finally overwrites the color value with neon red, as an example.
Conclusions
Web Components offer the web developer an important design pattern for integrating small microservices into their websites. Custom elements enable you to design universal declarative identifiers for the components. The shadow DOM reduces conflicts with the rest of the document and provides interfaces for programming and formatting. Use of the design pattern is cultivated by Google's Polymer open source framework, which provides an entire zoo of ready-made Web Components free of charge.
Infos
- Web Components: https://www.webcomponents.org
- Polymer: https://www.polymer-project.org
- X-Tag by Mozilla: https://x-tag.github.io
- Mozilla on Web Components: https://developer.mozilla.org/en-US/docs/Web/Web_Components
- Firefox Web Components API: https://hacks.mozilla.org/2018/10/firefox-63-tricks-and-treats/
- Design patterns: https://www.webcomponents.org/introduction
- Custom elements: https://w3c.github.io/webcomponents/spec/custom/
- Shadow DOM: https://w3c.github.io/webcomponents/spec/shadow/
- HTML templates: https://html.spec.whatwg.org/multipage/scripting.html#the-template-element
- JavaScript module system: https://html.spec.whatwg.org/multipage/webappapis.html#integration-with-the-javascript-module-system
- Node package archive: http://www.npmjs.org
« Previous 1 2 3 4 5
Buy this article as PDF
(incl. VAT)