Search code examples
csscss-gridsveltesvelte-component

How to use CSS Grid globally in Svelte?


I'm using CSS Grids to achieve this layout and just for reference, the desired behavior is that when users scroll down the page all the text remain fixed while the rest of the content slides over, something like this. I've managed to achieve this by creating a Home.svelte component and adding a .grid class to the <main>. This is what my CSS looks like:

.grid {
height: 100vh; 
display: grid; 
gap: 0px; 
grid-template-columns: 9% 18% 27% 46%; 
grid-template-rows: 9% 24% 22% 45%; 
}

But as you can see there is going to be a Thoughts link that behaves like a <nav> element on the top and possibly another pages as well and the problem I'm having is: for every new Svelte component that works as a route (I'm using svelte-spa-router) I need to add the same <main class="gird"> and that CSS code snippet. And this makes adding the page-specific content messy. I was hoping to be able to use all those elements as some kind of layout. Tried to add then to a Svelte component that I would then import but I was unable to do so because things wouldn't fit in the grid, it seems like they were following the normal flow.

I was wondering if it would be possible to somehow make this style global so I don't need to replicate it for every other page. I tried to apply these grid properties to body and html in my app.css (which is where all my CSS variables are attached to :root) file without success as the styles apparently aren't even applied to other pages. I even tried adding these stylings under something like :global(.grid) inside the app.css file but again, had the same outcome.

Any ideias or suggestions on how to handle this and avoid the code repetition? Where should these grid stylings live in a Svelte project? What are the best practices here? Thanks in advance!


Solution

  • In a regular CSS file that is linked in the page, you don't need :global.
    In a component's <style> you do need it.

    Check the styles that the page actually loads (e.g. via the network tab in the dev tools) and see if the rules actually exist and match what you expect.