Using CSS Pre-processors

Like post-processing, there are CSS pre-processors too. CSS pre-processors solves the flexibility and reusability problems in CSS. It will be hard to manage CSS for large applications.

Nowadays, CSS supports a lot of magic done by pre-processors. That makes the pre-processors less glamourous. But before a few years, CSS pre-processors are like jQuery for writing CSS.

Some of the CSS pre-processors are,

  • SCSS/SASS
  • LESS
  • Stylus

Some of the common functionalities CSS pre-processors adds on top of regular CSS are,

  • Variables - Now CSS3 also supports variables
  • Nested CSS
  • Partials - Like HTML template partials, you can reuse a part in many CSS classes
  • Modules - like importing JS modules, you can import CSS sheets as modules
  • Mixin -like JS functions to reuse or autogenerate CSS

We are going to convert our FAQ component's CSS to SCSS.

Check out this SCSS guide if you don't know it. To support SCSS files, we need to install node-sass.

yarn add node-sass@4.14.1

react-scripts will auto detact the node-sass and pre-process the .scss file extensions.

We have a detailed blog post on adding SCSS support in a React app here.

Let's convert our faq.css to faq.scss file,

// SCSS Variable definitions
$textColor: #65687d;

.faq {
  padding: 48px;
  border: 1px solid #e7e9f3;
  border-radius: 24px;
  background-color: #fff;
  box-shadow: 0 4px 8px 0 rgba(117, 131, 253, 0.09);
  transition: transform 350ms ease, box-shadow 350ms ease, color 300ms ease, -webkit-transform
      350ms ease;
  text-decoration: none;

  // Question and Answer text styles
  &-question {
    color: #354fe7;
    margin-bottom: 8px;
    font-size: 22px;
    line-height: 30px;
    font-weight: bold;
    transition: color 300ms ease;
  }
  &-answer {
    color: $textColor;
    margin-bottom: 24px;
    font-size: 18px;
    line-height: 28px;
  }
  // Details block
  &-details {
    display: flex;
    align-items: center;
  }
  // Date text
  &-date {
    color: $textColor;
    margin-bottom: 0px;
    font-size: 16px;
    line-height: 18px;
  }

  // Author block
  &-author {
    &-image {
      width: 48px;
      height: 48px;
      margin-right: 16px;
      border-radius: 50%;
    }
    &-name {
      color: #222433;
      margin-bottom: 8px;
      font-size: 18px;
      line-height: 18px;
      font-weight: bold;
    }
  }
}

You can see the code in action here,