Search code examples
csssveltesveltekitui-design

Media queries vs. svelte:window innerWidth - Which one is better way to build a responsive UI in svelte?


While building a responsive webpage using sveltekit, I found two ways to render different UIs depending on the device width: media queries and bind:innerWidth with svelte:window.

Media query seems to be used very widely in web UI development. According to the device width we set the css display property none or the others. With display: none, the element disappears from the view.

The other way is using <svelte:window bind:innerWidth />. In this way we can bind the window size to a variable and then use the value in <script>. Then we can conditionally render elements using if blocks.

So I got a question. Which way is better in two aspects: optimization and clean code? Considering more details we have numerous ways to build the responsive design, and which way would you choose to achieve this?


Solution

  • It depends.

    If you can solve whatever you are trying to do just with styles, I would generally recommend that. If you need sizing logic in code, then using one of the bindings or the new reactive media query wrapper is helpful.

    In terms of optimization, combining size information with #if can be helpful since the contents are never rendered if the condition is false. If you just hide and unhide elements with CSS, they still have to be created first.

    Though in most cases this should not matter too much, but if you e.g. completely replace the page contents depending on viewport size it might be worth it.