More on CSS

We've only scratched the surface of CSS in the last two chapters. Over the decades, CSS has grown from a fairly limited styling language to really one of the most effect layout and user interface languages in software development. CSS's declarative syntax is vastly superior to procedural code like JavaScript, when it can replace it. The good news is that for so many of the things we used to need to do with client-side JavaScript, we can now specify in CSS. Here's some examples:

  • CSS Transitions allow property changes (e.g., color, size, position) to happen gradually over a specified duration instead of instantly. They require a starting state and an ending state, with changes triggered by user interactions like hovering or clicking. Example: transition: all 0.5s ease-in-out;. You can learn a lot more about transition here.
  • CSS Animations offer more control over movement and effects, allowing multiple stages (keyframes) and looping. They don’t require user interaction to start and can be used for more complex effects. Example: @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }. Animations also allow you to specify motion paths of elements in incredible detail, along with tying animation events to all sorts of things - like scrolling. Check out more examples here.

The advantage of using CSS over client-side JavaScript will become more apparent as we cover client-side JavaScript later on - but it can be summed up as follows: when you specify something in CSS, you are specifying what you want to happen, and the browser takes care of the how part. When you use client-side JavaScript, your code is responsible for what happens AND how it happens. Use CSS when it can do the job for you, because you leverage the browser's implementations - which have an enormous amount of developer hours behind them, and a whole lot of testing. Use JavaScript to get the job done as a last resort.