Divide and conquer

pull/7161/head
Nayan Gautam 4 years ago
parent 61a549e4ec
commit 6a2a944cae

@ -5,7 +5,7 @@
<input type="range" min="0" max="1" step="0.1" bind:value={bgOpacity} />
<p style:color style:--opacity={bgOpacity}>This is a paragraph.</p>
<p style="color: {color}; --opacity: {bgOpacity};">This is a paragraph.</p>
<style>
p {

@ -8,14 +8,3 @@ Add the following style attribute to the paragraph element:
`style="color: {color}; --opacity: {bgOpacity};"`
Great, now you can style the paragraph using variables that change based on your input without having to make a class for every possible value.
This can however get unwieldly if you have to write a rather long string, and missing any of the semicolons will make it invalid. Svelte provides a nicer way to write inline styles and that is to use the style directive like this:
```html
<p
style:color
style:--opacity={bgOpacity}
>
```
They share a few qualities with class directives. You can use a shorthand when the name of the property and the variable are the same. So `style:color="{color}"` can be written as just `style:color`. Another is that the directives will take precedence when you set the same property through a style attribute.

@ -0,0 +1,15 @@
<script>
let bgOpacity = 0.5;
$: color = bgOpacity < 0.6 ? '#000' : '#fff';
</script>
<input type="range" min="0" max="1" step="0.1" bind:value={bgOpacity} />
<p style="color: {color}; --opacity: {bgOpacity};">This is a paragraph.</p>
<style>
p {
font-family: "Comic Sans MS", cursive;
background: rgba(255, 62, 0, var(--opacity));
}
</style>

@ -0,0 +1,15 @@
<script>
let bgOpacity = 0.5;
$: color = bgOpacity < 0.6 ? "#000" : "#fff";
</script>
<input type="range" min="0" max="1" step="0.1" bind:value={bgOpacity} />
<p style:color style:--opacity={bgOpacity}>This is a paragraph.</p>
<style>
p {
font-family: "Comic Sans MS", cursive;
background: rgba(255, 62, 0, var(--opacity));
}
</style>

@ -0,0 +1,16 @@
---
title: Inline styles and the style directive
---
Being able to set css properties dynamically is nice, however this can get unwieldly if you have to write a long string, and mistakes like missing any of the semicolons could make the whole string invalid. Therefore, Svelte provides a nicer way to write inline styles with the style directive.
Change the style attribute of the paragraph to the following:
```html
<p
style:color
style:--opacity="{bgOpacity}"
>
```
Style directives share a few qualities with class directives. You can use a shorthand when the name of the property and the variable are the same. So `style:color="{color}"` can be written as just `style:color`. And just like class directives, the directives will take precedence if you set the same property through a style attribute.
Loading…
Cancel
Save