Utilizing media queries is a viable solution.
You can create classes that display or hide an element based on the viewport width. This method either requires a wrapper element for applying styles, or you can define the rules globally, pass the class to components, and apply them there.
For example:
<div class="show-large">
<TableDisplay/>
</div>
<div class="show-small">
<CardsDisplay/>
</div>
<style>
/* `contents` prevents wrapper from affecting layout */
.show-small { display: none; }
.show-large { display: contents; }
@media (max-width: 768px) {
.show-small { display: contents; }
.show-large { display: none; }
}
</style>
Check out this REPL Example
It's important to note that this approach differs from using {#if}
:
When using media queries, all elements and components are created and inserted into the document, even if they are not always displayed, whereas {#if}
does not create anything if the condition is not met.