Efficiently apply inline styles to Svelte components.
NPM users: please consider the Github README for the latest description of this package (as updating the docs would otherwise always require a new NPM package version)
Just a small note: if you like this module and plan to use it, consider "starring" this repository (you will find the "Star" button on the top right of this page), so that I know which of my repositories to take most care of.
npm install svelte-inline-style
It is recommended to import the package within a module context:
<script context="module">
import style from 'svelte-inline-style'
</script>
<script>
let styles = {
fontSize:'22px', // use camel-cased CSS property names...
fontWeight:'bold' // ...and start with a small letter
}
</script>
<div use:style={styles}>...</div>
Experiment with svelte-inline-style
using the Svelte REPL
Sometimes it is necessary to add inline styles to a Svelte component rather than to rely on a stylesheet and just switch classes.
A straightforward approach could be to use style
attributes:
<div style="font-size:{fontsize}px; font-weight:{fontweight}">...</div>
but this one would first require to construct a string which would then have to parsed by the browser before the actual changes could be made.
Another solution has been shown by mouse484 in package svelte-inline-css: with the aid of Svelte "actions" inline styles may be directly set on the HTML elements created to represent Svelte components:
<script>
import style from 'svelte-inline-css'
export let styles = {
'font-size':'22px',
'font-weight':'bold'
}
</script>
<div use:style={styles}>...</div>
This solution works great, but - again - requires some string processing before the actual style can be applied: svelte-inline-css
expects kebab-cased CSS property names which first have to be converted to camel-cased identifiers before they may be set.
This implementation therefore suggests a third alternative, which seems "more natural": start with camel-cased CSS property names right away and apply them to HTML elements without prior conversion.
<script>
import style from './svelte-inline-style.js'
export let styles = {
fontSize:'22px',
fontWeight:'bold'
}
</script>
<div use:style={styles}>...</div>
You may easily build this package yourself.
Just install NPM according to the instructions for your platform and follow these steps:
- either clone this repository using git or download a ZIP archive with its contents to your disk and unpack it there
- open a shell and navigate to the root directory of this repository
- run
npm install
in order to install the complete build environment - execute
npm run build
to create a new build
You may also look into the author's build-configuration-study for a general description of his build environment.