Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CSS in JS

CSS in JS

In this talk we will go through the main problems with CSS at scale and we will see some interesting JavaScript-based solutions, from Inline Styles to CSS Modules. Are you ready to enter the magical world of CSS in JS?

Michele Bertoli

April 28, 2016
Tweet

More Decks by Michele Bertoli

Other Decks in Programming

Transcript

  1. Michele (Mee-keh-leh) Front End Developer at YPlan Member of WEBdeBS

    Follow me @MicheleBertoli I’ve got the CSSinJS skill on LinkedIn
  2. Problems with CSS at scale (vjeux) - Global Namespace -

    Dependencies - Dead Code Elimination - Minification - Sharing Constants - Non-deterministic Resolution - Isolation
  3. const divStyle = { color: 'white', backgroundImage: `url(${imgUrl})`, WebkitTransition: 'all',

    msTransition: 'all', }; ReactDOM.render( <div style={divStyle}>Hello World!</div>, mountNode );
  4. Cons - Pseudo classes/elements - Media queries - Style fallbacks

    - Animations - !important - Separation of concerns - Performance (?)
  5. import { StyleSheet, css } from 'aphrodite'; const styles =

    StyleSheet.create({ btn: { color: 'red' } }); el.innerHTML = `<button class="${css(styles.btn)}">Yo</button>`;
  6. const styles = StyleSheet.create({ hover: { ':hover': { color: 'red'

    } }, small: { '@media (max-width: 600px)': { color: 'red' } }, });
  7. const sheet = cssx(); const button = sheet.add('.button', { color:

    'red', }); button.update({ color: 'green', });
  8. CSSX CSSX is a set of tools that will help

    you write vanilla CSS in JavaScript.
  9. // button.css .common { color: red; } // button.js import

    styles from "./button.css"; el.innerHTML = `<button class="${styles.common}">Yo</button>`;
  10. CSS Modules A CSS Module is a CSS file in

    which all class names and animation names are scoped locally by default.
  11. Webpack module.exports = { module: { loaders: [ { test:

    /\.css$/, loader: 'style-loader!css-loader' } ] } };
  12. @media screen and (min-width: 48em) { .f3-ns { font-size: 1.5rem;

    } } .f4 { font-size: 1.25rem; } .mb0 { margin-bottom: 0; } .fw6 { font-weight: 600; } <h2 class="f4 f3-ns fw6 mb0">Responsive</h2>
  13. Atomic CSS The bad parts: - Too many classes -

    Similar to inline styles - Hard to maintain The good parts: - Quick prototyping - CSS file size
  14. Atomic CSS Modules .title { composes: fw6 f4 f3-ns from

    './fonts.css'; composes: mb0 from './margins.css'; } <h2 class="${styles.title}">Responsive</h2>
  15. Recap - Use the right tool, no matter if it

    breaks the rules - Inline styles vs local scope - Appearance vs state - Have fun :)