CSS
The Duck way of implementing CSS. Or, just do ordinary CSS files. Either way!
Demo
live demo | files
Recipe
In Practice
You only need to focus on the default
data.cssId
and
the CSS inside the update()
function. You can actually ignore everything else.
Walkthrough
Duck is JavaScript-centric. So, naturally, CSS in Duck should be JavaScript-centric as well.
To implement CSS in Duck, you can use a “Css Duck”. A Css Duck has a single responsibility, and that is to manage a
<style>
tag.
A Css Duck simply appends a style tag to the head of the document and updates it when update()
is called.
However, if the style tag is already in the document head, there is no need to re-append it.
To solve this, we simply add an id to the style tag and simply check if an element exists with the id before appending it.
To support multiple variations of the same CSS but with different values,
you can pass different values for cssId, and the Css Duck will keep references to the various
<style>
tags.
Notes
Css Ducks are still Ducks
You must pass in a fresh
data
object when creating a Css Duck.
Using traditional CSS files
If you want to write your CSS inside a traditional .css file, simply use a
<link>
tag,
When using a
<link>
tag, there's no need to have multiple cssId's since you can't modify values of a static CSS file,
hence the StaticCss.instance
instead of StaticCss[data.cssId]
.
But, feel free to use
StaticCss[data.cssId]
! It doesn't make a difference!
Additionally, a CSS file obviously cannot be updated, so there is no update function.
Component CSS
I like to write my CSS for a component in the same file as the component itself.
One way is to make a Css Duck as a static property of the
Component
itself.
You can also just make a Css Duck named something like, ComponentCss
. That works as well!