Web components are a set of powerful tools that allow you to create your own custom HTML elements. These elements can be used just like any other HTML tag (e.g., <div>, <span>) but with your own special behavior and design.
The core technologies behind web components are:
: Keeps your element’s structure and styles isolated from the rest of the page.
Here is the .
counter.js with Styling
CODE...
connectedCallback() {
...
this.attachShadow({ mode: 'open' });
// Add styles to the component
const sheet = new CSSStyleSheet();
sheet.replaceSync(this.styles());
this.shadowRoot.adoptedStyleSheets = [sheet];
// Clone the template and add it to our custom element's shadow DOM
this.shadowRoot.appendChild(template.content.cloneNode(true));
...
}
...
styles() {
return `
:host {
display: block;
border: dotted 3px #333;
width: fit-content;
height: fit-content;
padding: 15px;
}
button {
border: solid 1px #333;
padding: 10px;
min-width: 35px;
background: #333;
color: #fff;
cursor: pointer;
}
button:hover {
background: #222;
}
span {
display: inline-block;
padding: 10px;
width: 50px;
text-align: center;
}
`
}
...
...
Conclusion
In this tutorial, we learned how to create a simple web component:
- We used an HTML template to define the structure of our custom element.
- We added shadow DOM to isolate the styles and behavior of our component.
- We wrote JavaScript to control the logic of the counter (increment, decrement, and display the count).
Web components are a great way to make your web applications more modular and reusable. Now that you know the basics, you can experiment with more complex components, like adding custom styles or animations to your elements.
↗ Original-Artikel auf dev.to lesenVollständiger Original-BerichtAusführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
SOCIAL SHARE CARD GENERATOR