When to use css vs javascript

My article on Friday about overengineering CSS apparently hit a chord with a lot of readers.

The responses I got were a mix of “hell yes!” and “how do you approach CSS in your projects?” Today, I wanted to talk more about when I use CSS vs. JavaScript.

CSS before JS

My general rule of thumb is…

If something I want to do with JavaScript can be done with CSS instead, use CSS.

CSS parses and renders faster.

For things like animations, it more easily hooks into the browser’s refresh rate cycle to provide silky smooth animations [this can be done in JS, too, but CSS just makes it so damn easy].

And it fails gracefully.

A JavaScript error can bring all of the JS on a page to screeching halt. Mistype a CSS property or miss a semicolon? The browser just skips the property and moves on. Use an unsupported feature? Same thing.

You can take this rule too far, though

A few years ago, there was an obsession with finding creative CSS hacks for things that would normally be done in JS.

A CSS-only expand/collapse navigation menu is the one that jumps to mind. Here’s an example. These are really cool examples of pushing CSS farther and thinking about code creatively, but…

The results are often wildly inaccessible.

Here’s the demo from the example I linked to. Hover over About or Portfolio. Works great!

Now, reload the page and try to tab through the menu. Nothing shows up. You can access the submenus below those items if you’re a keyboard only user.

There are times where, for accessibly, using JavaScript is actually better than using CSS.

A mental model for making decisions

I don’t really have a formal model for choosing when to use CSS vs. JS, but approach to which one to use and when looks like this:

  • If the item requires interaction from the user, use JavaScript [things like hovering, focusing, clicking, etc.].
  • If the item needs to change in visibility, needs to be animated, or have any other visual change made to is, use CSS.

Often times, these two are combined.

For example, let’s talk about the drop-down menu example we looked at earlier. You can detect focus on the drop-down link with CSS, but once you tab into the links below it, the original link loses focus.

I would use JavaScript to detect a change in focus, and then check if the currently in focus element is either that link or one of the items below it.

If either of those conditions is true, I would add a class to the dropdown menu that makes it visible. You could also use that class to add animations and do all sort of other fun stuff.

Tomorrow, I’m going to talk about my preferred CSS methodologies, and how I use them to write stylesheets that are absurdly tiny and performant.

I'm working on a responsive design would like to know if it is better to style an element using JavaScript or with CSS? CSS is certainly easier to maintain, I won't argue that, but I'm a lot more comfortable building an object in JavaScript. Maybe I'm making more work for myself than I should, but I feel like I have more control overall and I like being able to hook into every object on the screen.

I have constructors that generate the entire page layout and push it into the DOM. No images, just pure JavaScript styling and SVG icons.

What I would like to know is:

  • What performs better?
  • What, if any hardware support is there for JS or CSS?
  • Is a pure JavaScript solution better than using CSS Calc[]?
  • What's more portable?
  • What's more forward compatible?

I tend to avoid jQuery as I'm more interested in learning what makes things work right now, so pure JavaScript and CSS3 only, please.

asked Oct 4, 2013 at 18:36

Ryan DunphyRyan Dunphy

7622 gold badges10 silver badges31 bronze badges

7

Your styling should be done using CSS wherever possible. Have different classes setup according to your needs, then add or remove classes when absolutely necessary with JS.

One thing to keep in mind is that changing styling via JS is a one-time change. Elements added dynamically VIA Ajax won't inherit the styling changes automatically. Another good reason to stick with CSS.

See this post for additional confirmation Should I load responsive design via JS or CSS

As suggested in the link

Putting everything regarding styles in the CSS files is the best practice.

HTML => Structure

CSS => Styles

JS => Logic

answered Oct 4, 2013 at 18:38

adamadam

2,9107 gold badges51 silver badges88 bronze badges

CSS is the best way to style an [X]HTML document.

Even if you need to style a document by using raw JavaScript or DOM, or some framework like jQuery, it'll mean you're giving values to CSS rules.

The rule should be:

  • Use pure CSS when you can style a predictable document - also you can enhance your CSS and use CSS selectors for generalized or complex scenarios -.

  • Use JavaScript/DOM or frameworks like JavaScript when document or portions of it aren't predictable or are created on-the-fly and you're applying special effects like fades or any other - in fact, CSS 3.0 has transitions so it's possible to do a lot of things without JavaScript -.

After all, think how simpler can be things done with CSS and what kind of overkill is using JavaScript instead, and keep in mind its cons [a very important point: browser compatibility and performance].

The more CSS you use, the more standarized, cross-browser, performant and maintainable web.

answered Oct 4, 2013 at 18:41

2

UI should be left to UI solutions [HTML/CSS]. JavaScript should only provide additional functionality.

To supplement this [because you mention CSS3] if you're referring to animations and new additions to CSS3 [that may not otherwise be available] you can use javascript--but only as a fallback. [e.g. using jQuery's fadeTo over creating an animation timeline with CSS3].

answered Oct 4, 2013 at 18:38

Brad ChristieBrad Christie

98.8k16 gold badges149 silver badges198 bronze badges

There are serious drawbacks when applying styles with JavaScript, not only because you have no control over specificity, it is slow [as you'd expect], any .css[] calls involving classes, e.g. $['.something'].css[...], will apply css to only elements of that class that exist at the time, not .somethings created in the future.

answered Oct 4, 2013 at 18:48

BrianBrian

6,9543 gold badges24 silver badges44 bronze badges

1

Should I use CSS or JavaScript?

If the item requires interaction from the user, use JavaScript [things like hovering, focusing, clicking, etc.]. If the item needs to change in visibility, needs to be animated, or have any other visual change made to is, use CSS.

Is CSS more efficient than JavaScript?

CSS has fairly good performance as it offloads animation logic onto the browser itself. This lets the browser optimize DOM interaction and memory consumption and most importantly, uses the GPU to improve performance. On the other hand, Javascript performance can range from reasonably faster to much slower than CSS.

Should I write CSS or JavaScript first?

To be a front end developer, you'll need to be proficient in all three of these languages, as they are constantly working together. Ideally you'll learn HTML first, then CSS, and then finish with JavaScript, as they build on each other in that order.

Do you need CSS if you know JavaScript?

That's because JS uses the DOM to access and manipulate web page content. The DOM wouldn't exist without HTML tags, and CSS is used to style that content. Therefore, if you want to learn JavaScript, it's essential that you first learn HTML and CSS.

Chủ Đề