{"id":25275,"date":"2024-03-27T08:27:12","date_gmt":"2024-03-27T07:27:12","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/domina-el-shadow-dom-estilizacion-y-encapsulamiento-en-componentes-web-2\/"},"modified":"2024-06-03T17:40:21","modified_gmt":"2024-06-03T16:40:21","slug":"domina-el-shadow-dom-estilizacion-y-encapsulamiento-en-componentes-web-2","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/","title":{"rendered":"Master the Shadow DOM: Stylization and Encapsulation in Web Components"},"content":{"rendered":"<p>Modern web development has advanced tremendously in recent years, and with it, the need for more encapsulated and reusable components. One of the most powerful tools to achieve this is the Shadow DOM, an essential part of the Web Components technology suite. The Shadow DOM allows web developers to keep the style and behavior of their components independent from the rest of the page, thus avoiding conflicts and keeping the code clean and maintainable.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#%C2%BFQue_es_el_Shadow_DOM\" >What is Shadow DOM?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Implementacion_del_Shadow_DOM_en_tus_Componentes\" >Implementation of the Shadow DOM in your Components<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Estilos_en_el_Shadow_DOM\" >Styles in the Shadow DOM<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Estrategias_para_Estilizar_el_Shadow_DOM\" >Strategies for Styling the Shadow DOM<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Hojas_de_Estilo_Externas\" >External Style Sheets<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Variables_CSS_y_Custom_Properties\" >CSS Variables and Custom Properties<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Slots_y_Estilos_Dinamicos\" >Slots and Dynamic Styles<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Buenas_Practicas_de_Estilizacion_en_Shadow_DOM\" >Good Styling Practices in Shadow DOM<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Evitar_la_Sobre-especificacion_de_Selectores\" >Avoid Over-specification of Selectors<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Uso_Balanceado_de_host_y_host-context\" >Balanced use of :host and :host-context()<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Polimeras_de_Estilos\" >Style Polymers<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Integracion_con_Frameworks_y_Herramientas_de_Construccion\" >Integration with Frameworks and Construction Tools<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-shadow-dom-stylization-and-encapsulation-in-web-components-2\/#Conclusion_El_Shadow_DOM_es_tu_Aliado\" >Conclusion: The Shadow DOM is your Ally<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"%C2%BFQue_es_el_Shadow_DOM\"><\/span>What is Shadow DOM?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Shadow DOM is a feature of the Web Components standard that allows you to encapsulate the DOM and CSS of a component. This way, styles defined within the Shadow DOM will not affect the &quot;light&quot; or main DOM of the document, and vice versa. This feature is essential for creating web components that are consistent in their presentation, no matter where they are used.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Implementacion_del_Shadow_DOM_en_tus_Componentes\"><\/span>Implementation of the Shadow DOM in your Components<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>To get started with the Shadow DOM, you must first create a new element that extends the class <code>HTMLElement<\/code>. Once this is done, you can attach a shadow root to the element using the method <code>attachShadow<\/code>.<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">class MyCustomComponent extends HTMLElement { constructor() { super(); this.attachShadow({ mode: &#039;open&#039; }); } }<\/code><\/pre>\n<p>The method <code>attachShadow<\/code> receives a configuration object, where <code>mode<\/code> could be <code>&#039;open&#039;<\/code> o <code>&#039;closed&#039;<\/code>. If you choose <code>&#039;open&#039;<\/code>, you can access the shadow DOM from outside the component. On the other hand, <code>&#039;closed&#039;<\/code> It completely encapsulates the shadow DOM, making it inaccessible from the main DOM.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Estilos_en_el_Shadow_DOM\"><\/span>Styles in the Shadow DOM<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>One of the most important benefits of the shadow DOM is its ability to encapsulate styles. By defining styles within the shadow root, we are ensuring that they will not be affected by the styles defined in the rest of the page, nor will they affect other elements outside the shadow DOM.<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">class MyCustomComponent extends HTMLElement { constructor() { super(); this.attachShadow({ mode: &amp;#039;open&amp;#039; }); this.shadowRoot.innerHTML = `\n          &lt;style&gt;\n            p {\n                color: blue;\n            }\n          &lt;\/style&gt;\n          &lt;p&gt;My custom component&lt;\/p&gt;\n        `;\n    }\n}<\/code><\/pre>\n<p>In this example, any paragraph <code>&lt;p&gt;<\/code> inside the shadow DOM <code>MyCustomComponent<\/code> will be displayed in blue, regardless of the styles defined on the main page.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Estrategias_para_Estilizar_el_Shadow_DOM\"><\/span>Strategies for Styling the Shadow DOM<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Hojas_de_Estilo_Externas\"><\/span>External Style Sheets<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>It is possible to reference external style sheets within the shadow DOM. However, due to encapsulation, these must be explicitly included in the shadow root of the component.<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const externalStyles = document.createElement(&#039;link&#039;); externalStyles.setAttribute(&#039;rel&#039;, &#039;stylesheet&#039;); externalStyles.setAttribute(&#039;href&#039;, &#039;my-style.css&#039;); this.shadowRoot.appendChild(externalStyles);<\/code><\/pre>\n<p>This will allow <code>my-style.css<\/code> apply only to the content of your component, without affecting the rest of the page.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Variables_CSS_y_Custom_Properties\"><\/span>CSS Variables and Custom Properties<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>CSS variables, also known as custom properties, are a great way to allow some styling flexibility in the Shadow DOM. Custom properties defined in the main document can be inherited within the shadow DOM, as long as you use the property <code>inherit<\/code> or initial values for them.<\/p>\n<pre><code class=\"&quot;language-css&quot;\">:host { --main-color: blue; } p { color: var(--main-color, black); }<\/code><\/pre>\n<p>In this case, <code>--main-color<\/code> can be defined anywhere on the page and will be applied within your component, unless you have defined a fallback value like <code>black<\/code>.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Slots_y_Estilos_Dinamicos\"><\/span>Slots and Dynamic Styles<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Slots are insertion points in the shadow DOM that allow content to be projected from the main DOM. You can assign styles to slots and the content projected within them.<\/p>\n<pre><code class=\"&quot;language-html&quot;\">&lt;mi-componente-personalizado&gt;\n    &lt;span slot=&quot;mensaje&quot;&gt;Hello World&lt;\/span&gt;\n&lt;\/mi-componente-personalizado&gt;<\/code><\/pre>\n<pre><code class=\"&quot;language-javascript&quot;\">this.shadowRoot.innerHTML = `\n    ::slotted(span) {\n        font-weight: bold;\n    }\n  `;<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Buenas_Practicas_de_Estilizacion_en_Shadow_DOM\"><\/span>Good Styling Practices in Shadow DOM<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Evitar_la_Sobre-especificacion_de_Selectores\"><\/span>Avoid Over-specification of Selectors<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Since the styles in the shadow DOM are encapsulated, there is no need to use highly specific selectors, which can make your code cleaner and easier to maintain.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Uso_Balanceado_de_host_y_host-context\"><\/span>Balanced use of <code>:host<\/code> y <code>:host-context()<\/code><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The pseudo-selector <code>:host<\/code> allows you to apply styles to the host element of the shadow DOM. On the other hand, <code>:host-context()<\/code> allows you to apply styles based on some ancestor of the host in the main DOM.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Polimeras_de_Estilos\"><\/span>Style Polymers<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>For styles that are common to multiple components, you might consider creating style sheets that can be imported and applied to multiple shadow roots, promoting reusability and consistency.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Integracion_con_Frameworks_y_Herramientas_de_Construccion\"><\/span>Integration with Frameworks and Construction Tools<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>When you work with frameworks like React, Vue or Angular, or tools like Webpack, you must consider how the shadow DOM interacts with these environments. Sometimes it may be necessary to configure additional loaders or plugins to support the import of styles within the shadow DOM.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion_El_Shadow_DOM_es_tu_Aliado\"><\/span>Conclusion: The Shadow DOM is your Ally<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The Shadow DOM is a powerful tool in your arsenal as a web developer. Although its implementation may require a bit of adaptation in your usual development practices, the benefits in terms of encapsulation, modularity and reusability of your components are definitely worth it.<\/p>\n<p>If you are looking for more information about developing with Web Components or the Shadow DOM, I invite you to visit <a href=\"https:\/\/nelkodev.com\/en\/\">NelkoDev<\/a>, where you will find additional resources and can contact me directly through <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">my contact page<\/a> for any questions or assistance in your web development projects. Best of luck in your exploration of the Shadow DOM!<\/p>","protected":false},"excerpt":{"rendered":"<p>El desarrollo web moderno ha avanzado tremendamente en los \u00faltimos a\u00f1os, y con \u00e9l, la necesidad de tener componentes m\u00e1s encapsulados y reusables. Una de las herramientas m\u00e1s potentes para lograr esto es el Shadow DOM, una parte esencial del conjunto de tecnolog\u00edas Web Components. El Shadow DOM permite a los desarrolladores web mantener el [&hellip;]<\/p>","protected":false},"author":1,"featured_media":25276,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420],"tags":[205,669,743,1473,1663,1664,722,47],"class_list":["post-25275","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","tag-blog","tag-componentes","tag-dom","tag-domina","tag-encapsulamiento","tag-estilizacion","tag-shadow","tag-web"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/25275","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=25275"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/25275\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/25276"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=25275"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=25275"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=25275"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}