Description
Describe the problem
The tailwind v4 alpha uses native cascade layers @layer
which can be read about on the MDN docs.
The component CSS that is rendered by sveltkit always puts CSS in the anonymous layer, which always takes precedence.
For example, a third party svelte component that looks like this:
<script>
const { class: clazz = '' } = $props();
</script>
<div class="blue { clazz }">WORDS</div>
<style>
:where(.blue) {
color: white;
background: blue;
}
</style>
And used like this
<script>
import Test from '$lib/test.svelte';
import './styles.css';
</script>
<Test class="bg-red-500" />
With styles.css being
@import "tailwindcss";
Will result in the background always being blue due to how CSS layers work with all the tailwind utility classes being the in the @utilities
, layer. I feel this is somewhat unexpected to a developer using a component with tailwind, especailly given the component author has tried to remove the problem by using the :where
pseudo class.
Describe the proposed solution
I'm wondering if an option should be added to the sveltekit config to allow component CSS to be wrapped in a layer so it can be handled better with native CSS layers.
I've had success using this preprocess function (in Svelte 5)
function svelteCssLayer(layerName) {
return {
name: 'svelte-css-layer',
style: ({ content }) => {
return {
code: `@layer ${layerName} { ${content} }`
}
},
}
}
My svelte.config.js
file then looks like this.
/** @type {import('@sveltejs/kit').Config} */
export default {
preprocess: [svelteCssLayer('svelte'), vitePreprocess()],
kit: {
adapter: adapter()
}
};
And my styles.css
changes to:
@layer theme, base, svelte, components, utilities;
@import "tailwindcss";
I have a codesandbox here that puts it all together.
Alternatives considered
No response
Importance
nice to have
Additional Information
I think as tailwind v4 adoption grows, this is likely to become a larger issue. I'm not sure if this should target sveltekit, or svelte itself but I felt this interesting enough to raise an issue about.