Cljss
Clojure Style Sheets — CSS-in-JS for ClojureScript
Install / Use
/learn @clj-commons/CljssREADME
Clojure Style Sheets
<img src="logo.png" width="155" height="68" alt="cljss logo" />CSS-in-JS for ClojureScript
Ask questions on #cljss chat at Clojuarians Slack
<a href="https://www.patreon.com/bePatron?c=1239559"> <img src="https://c5.patreon.com/external/logo/become_a_patron_button.png" height="40px" /> </a>[clj-commons/cljss "1.6.4"]
Table of Contents
- Why write CSS in ClojureScript?
- Features
- How it works
- Usage
- Composing styles
- Development workflow
- Production build
- Roadmap
- Contributing
- Supporters
- License
Why write CSS in ClojureScript?
Writing styles this way has the same benefits as writing components that keep together view logic and presentation. It all comes to developer efficiency and maintainability.
Thease are some resources that can give you more context:
- “A Unified Styling Language” by Mark Dalgleish
- “A Unified Styling Language” (talk) by Mark Dalgleish
- “The road to styled components: CSS in component-based systems” by Glen Maddern
Features
- Automatic scoped styles by generating unique names
- CSS pseudo-classes and pseudo-elements
- CSS animations via
@keyframesat-rule - CSS Media Queries
- Nested CSS selectors
- Injects styles into
<style>tag at run-time - Debuggable styles in development (set via
goog.DEBUG) - Fast, 1000 insertions in under 100ms
How it works
defstyles
defstyles macro expands into a function which accepts an arbitrary number of arguments and returns a string of auto-generated class names that references both static and dynamic styles.
(defstyles button [bg]
{:font-size "14px"
:background-color bg})
(button "#000")
;; "-css-43696 -vars-43696"
Dynamic styles are updated via CSS Variables (see browser support).
defstyled
defstyled macro accepts var name, HTML element tag name as a keyword and a hash of styles.
The macro expands into a function which accepts an optional hash of attributes and child components, and returns a React element. It is available for the Om, Rum and Reagent libraries. Each of them are in corresponding namespaces: cljss.om/defstyled, cljss.rum/defstyled and cljss.reagent/defstyled.
A hash of attributes with dynamic CSS values as well as normal HTML attributes can be passed into the underlying React element. Reading from the attributes hash map can be done via anything that satisfies cljs.core/ifn? predicate (Fn and IFn protocols, and normal functions).
NOTE: Dynamic props that are used only to compute styles are also passed onto React element and thus result in adding an unknown attribute on a DOM node. To prevent this it is recommended to use keyword or a function marked with with-meta so the library can remove those props (see example below).
- keyword value — reads the value from props map and removes matching attribute
with-metawith a single keyword — passes a value of a specified attribute from props map into a function and removes matching attributewith-metawith a collection of keywords — passes values of specified attributes from props map into a function in the order of these attributes and removes matching attributes
(defstyled h1 :h1
{:font-family "sans-serif"
:font-size :size ;; reads the value and removes custom `:size` attribute
:color (with-meta #(get {:light "#fff" :dark "#000"} %) :color)} ;; gets `:color` value and removes this attribute
:padding (with-meta #(str %1 " " %2) [:padding-v :padding-h])) ;; gets values of specified attrs as arguments and remove those attrs
(h1 {:size "32px" ;; custom attr
:color :dark ;; custom attr
:padding-v "8px" ;; custom attr
:padding-h "4px" ;; custom attr
:margin "8px 16px"} ;; normal CSS rule
"Hello, world!")
;; (js/React.createElement "h1" #js {:className "css-43697 vars-43697"} "Hello, world!")
predicate attributes in defstyled
Sometimes you want toggle between two values. In this example a menu item can switch between active and non-active styles using :active? attribute.
(defstyled MenuItem :li
{:color (with-meta #(if % "black" "grey") :active?)})
(MenuItem {:active? true})
Because this pattern is so common there's a special treatment for predicate attributes (keywords ending with ?) in styles definition.
(defstyled MenuItem :li
{:color "grey"
:active? {:color "black"}})
(MenuItem {:active? true})
pseudo-classes
CSS pseudo classes can be expressed as a keyword using parent selector syntax & which is popular in CSS pre-processors or as a string if selector is not a valid keyword e.g. &:nth-child(4).
(defstyles button [bg]
{:font-size "14px"
:background-color blue
:&:hover {:background-color light-blue}
"&:nth-child(3)" {:color "blue"}})
Nested selectors
Sometimes when you want to override library styles you may want to refer to DOM node via its class name, tag or whatever. For this purpose you can use nested CSS selectors via string key.
(defstyles error-form []
{:border "1px solid red"
".material-ui--input" {:color "red"}})
[:form {:class (error-form)} ;; .css-817253 {border: 1px solid red}
(mui/Input)] ;; .css-817253 .material-ui--input {color: red}
:css attribute
:css attribute allows to define styles inline and still benefit from CSS-in-JS approach.
NOTE: This feature is supported only for Rum/Sablono elements
(def color "#000")
[:button {:css {:color color}} "Button"]
;; (js/React.createElement "button" #js {:className "css-43697 vars-43697"} "Button")
defkeyframes
defkeyframes macro expands into a function which accepts arbitrary number of arguments, injects @keyframes declaration and returns a string that is an animation name.
(defkeyframes spin [from to]
{:from {:transform (str "rotate(" from "deg)")
:to {:transform (str "rotate(" to "deg)")}})
[:div {:style {:animation (str (spin 0 180) " 500ms ease infinite")}}]
;; (js/React.createElement "div" #js {:style #js {:animation "animation-43697 500ms ease infinite"}})
font-face
font-face macro allows to define custom fonts via @font-face CSS at-rule. The macro generates CSS string and injects it at runtime. The syntax is defined in example below.
The macro supports referring to styles declaration in a separate *.clj namespace.
(require '[cljss.core :refer [font-face]])
(def path "https://fonts.gstatic.com/s/patrickhandsc/v4/OYFWCgfCR-7uHIovjUZXsZ71Uis0Qeb9Gqo8IZV7ckE")
(font-face
{:font-family "Patrick Hand SC"
:font-style "normal"
:font-weight 400
:src [{:local "Patrick Hand SC"}
{:local "PatrickHandSC-Regular"}
{:url (str path ".woff2")
:format "woff2"}
{:url (str path ".otf")
:format "opentype"}]
:unicode-range ["U+0100-024F" "U+1E00-1EFF"]})
inject-global
inject-global macro allows to defined global styles, such as to reset user agent default styles. The macro generates CSS string and injects it at runtime. The syntax is defined in example below.
The macro supports referring to styles declaration in a separate *.clj namespace.
(require '[cljss.core :refer [inject-global]])
(def v-margin 4)
(inject-global
{:body {:margin 0}
:ul {:list-style "none"}
"ul > li" {:margin (str v-margin "px 0")}})
CSS Media Queries
The syntax is specified as of CSS Media Queries Level 4 spec.
(require [cljss.core :as css])
(defstyles header [height]
{:height height
::css/media {[:only :screen :and [:max-width "460px"]]
{:height (/ height 2)}}})
- Supported media types:
#{:all :print :screen :speech} - Modifiers:
#{:not :only}
More examples of a query:
Boolean query
[[:monochrome]]
Simple conditional query
[[:max-width "460px"]]
Multiple (comma separated) queries
[[:screen :and [:max-width "460px"]]
[:print :and [:color]]]
Basic range query
Supported operators for range queries #{'= '< '<= '> '>=}
'[[:max-width > "400px"]]
Complex range query
'[["1200px" >= :max-width > "400px"]]
Usage
(defstyles name [args] styles)
namename of a var[args]argumentsstylesa hash map of styles definition
(ns example.core
(:require [cljss.core :refer-macros [defstyles]]))
(defstyles button [bg]
{:font-size "14px"
:background-color bg})
[:div {:class (button "#fafafa")}]
(defstyled name tag-name styles)
namename of a vartag-nameHTML tag name as a keywordstylesa hash map of styles definition
Using Sablono templating for React
(ns example.core
(:require [sablono.core :refer [html]]
[cljss.rum :refer [defstyled]]))
(defstyled Button :button
{:padding "16px"
:margin-top :v-margin
:margin-bottom :v-margin})
(html
(Button {:v-margin "8px"
:on-click #(console.log "Click!")}))
Dyna
