← Volver
Web Components
Publicado el 28 de agosto de 2026
Web
A la hora de desarrollar una web podemos crear componentes reutilizables con un código HTML y unas etiquetas personalizadas.
El index.html
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<title>Web Component Simple</title>
<script defer src="./assets/js/cardWidget.js" type="module"></script>
</head>
<body>
<h1>Mi Dashboard con Web Components</h1>
<p>
Las tarjetas a continuación son componentes web totalmente encapsulados.
</p>
<card-widget
name="Alicia Ramírez"
role="Desarrolladora Frontend"
></card-widget>
<card-widget
name="Roberto Gómez"
role="Arquitecto de Software"
></card-widget>
<div style="margin-top: 50px">
<h2>Otro componente más abajo</h2>
<card-widget name="Laura Pérez" role="Diseñadora UI/UX"></card-widget>
</div>
</body>
</html>
El código en cardWidget.css
:host {
display: block;
border: 1px solid #ccc;
padding: 20px;
margin-bottom: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
background-color: #002750;
}
h3 {
color: #007bff;
margin-top: 0;
font-size: 1.5em;
font-family:
"Trebuchet MS", "Lucida Sans Unicode", "Lucida Grande", "Lucida Sans",
Arial, sans-serif;
}
.role {
padding: 5px 10px;
border-radius: 4px;
display: inline-block;
font-style: italic;
color: #ffffff;
font-family: "Times New Roman", Times, serif;
background-color: #007bff;
}Y por último el cardWidget.js
const response = await fetch("./assets/css/cardWidget.css");
const cssText = await response.text();
const styles = new CSSStyleSheet();
styles.replaceSync(cssText);
class CardWidget extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.adoptedStyleSheets = [styles];
}
connectedCallback() {
const name = this.getAttribute("name") || "";
const role = this.getAttribute("role") || "";
this.shadowRoot.innerHTML = `
<div class="card-content">
<h3>${name}</h3>
<p class="role">Role: ${role}</p>
</div>
`;
}
}
customElements.define("card-widget", CardWidget);