Using Shadow DOM in components for styling and isolation is an intelligent choice. In this context, there are occasions when we may want to make changes in these styles, especially considering the widespread use of @media queries for crafting responsive user interfaces. You can directly style elements defined in Shadow DOM or edit them with script variables.
One way to modify styles is by using JavaScript to embed or change styles in Shadow styles. Specifically, you can gain access to related stylesheets and apply necessary changes yourself. If you haven’t experienced using shadow root, it’s essential to initially familiarize yourself with its basic concepts - a concept that includes encapsulation and in this case, accessibility.
Another effective method is to create a CSS class within the Shadow DOM that can be modified through JavaScript or HTML when necessary. This method is a simple and implementable solution that easily allows you to control changes and is simultaneously concise and maintainable.
A more permanent solution is to use @import
for importing external stylesheets into the shadow root. This method is less preferred because additional imports can complicate things, but it’s still a useful method in certain situations.
Example Code
<style>
.content {
color: black;
}
@media (max-width: 600px) {
.content {
color: blue;
}
}
</style>
<script>
let shadow = document.querySelector('#host').attachShadow({mode: 'open'});
shadow.innerHTML = '<style>
.content { color: black; }
@media (max-width: 600px) {
.content { color: blue; }
}
</style> <div class="content">Sample Content</div>';
</script>
Line-by-Line Explanation of Code
<style>
defines the internal stylesheet containing the elements that are to be displayed..content
is the base style class that is generally applied.@media
uses media query to apply changes in case of a change in page size.(max-width: 600px)
is the condition that checks if the page is less than 600px wide.color: blue;
changes the text color to blue when the condition is met.<script>
creates and attaches a shadow root in the HTML file.document.querySelector('#host')
selects the main element that acts as host.attachShadow({mode: 'open'})
creates a shadow root attached to the selected element.innerHTML
replaces the content inside the shadow root with specified styles and identified HTML.