Skip to content

Injecting styles into components #12802

@XIYO

Description

@XIYO

Describe the problem

Hello,

I always style my components with a no-JS environment in mind. I only use scripts to control the on/off state of styles when absolutely necessary.

As a result, I end up using :global quite a lot when applying styles to componentized elements.

Border.svelte

<script>
	let { classesOuter, classes } = $props();
</script>

<div class="outer" bind:class={classesOuter}>
	<div class="inner" bind:class={classes}>
		{@render children()}
	</div>
</div>

<style>
    .outer {
        border: 1px solid black;
        padding: 10px;
    }

    .inner {
        background-color: blanchedalmond;
    }
</style>

+page.svelte

<script>
	import Border from '$lib/Border.svelte';
</script>

<label>Show Menu
	<input type="checkbox"/>
</label>
<Border classes="nav">
	<nav>~~~</nav>
</Border>

<style>
	:global(.nav) {
			position: absolute;
			right: 0;
			top: 0;
	}

  input:not(:checked) + :global(.nav) {
      visibility: hidden;
  }
</style>

Describe the proposed solution

If components were designed to allow for style injection, the use of :global could be minimized, and the code would become more robust against errors since styles wouldn't rely on text literals for selection.

Border.svelte

<div class="outer" handlableElement>
	<div class="inner" >
		{@render children()}
		</div>
</div>

<style>
	.outer {
			border: 1px solid black;
			padding: 10px;
	}

	.inner {
			background-color: blanchedalmond;
	}
</style>

+page.svelte

<script>
	import Border from '$lib/Border.svelte';
</script>

<label>Show Menu
<input type="checkbox"/>
</label>
<Border><nav>~~~</nav></Border>

<style>
	$Border {
			position: absolute;
			right: 0;
			top: 0;
	}

	input:not(:checked) + $Border {
			visibility: hidden;
	}
</style>

Importance

nice to have

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions