Style utilities as Svelte actions
svelte-style
provides Svelte actions that conditionally apply styles as an alternative to writing CSS.
Try it in the Svelte REPL.
Yarn
yarn add -D svelte-style
NPM
npm i -D svelte-style
pnpm
pnpm i -D svelte-style
Use the visuallyHidden
action to hide content without breaking screen readers.
<script>
import { visuallyHidden } from "svelte-style";
</script>
<div use:visuallyHidden>Text</div>
The action accepts an argument that conditionally toggles the style.
<script>
import { visuallyHidden } from "svelte-style";
let toggled = false;
</script>
<button on:click={() => (toggled = !toggled)}>
Toggle <span style="color: red" use:visuallyHidden={toggled}>Text</span>
</button>
Create your own Svelte action that conditionally applies styles using the Style
class.
JavaScript
<script>
import { Style } from "svelte-style";
const style = "color: red";
const colorRed = (node, enabled) => new Style(node, enabled, style).init();
</script>
<div use:colorRed>Red text</div>
TypeScript
If your set-up includes TypeScript, use UseStyleType
to statically type the action.
import { Style } from "svelte-style";
import { UseStyleType } from "svelte-style/src/Style";
const style = "color: red";
const colorRed: UseStyleType = (node, enabled) => new Style(node, enabled, style).init();
Svelte version 3.31 or greater is required to use this component with TypeScript.
TypeScript definitions are located in the types folder.