Why to Use CSS Instead of JavaScript for Your Menus

Before I start on this post, if you haven’t read Good Tech Things to Know, I recommend you read that one first. I’ll be referencing what I wrote in that post for purposes of explaining the tech in this one. If you already have a basic understanding of what both JavaScript and CSS are and what they do, you’re welcome to hang out here, but the link’s still there if you need it.

That said, let’s dive into a lesson I learned very recently: why to use CSS instead of JavaScript for menus.

To start off, let’s explain what I mean by “menus”. A menu is just a place that a user can go to choose from different options; just like in a restaurant. In the context of websites and applications, menus can be used for navigation, selection, input, and more. There are a number of types of menus, but one of the most common, especially for navigation on websites, is a drop-down. Here’s an example. You can hover your mouse over the square labeled “Two” and get four additional options. Here’s another example. You can click on any of the squares with arrows and access additional options. This example is a bit more complicated, since hovering over some of the options shows yet more. Still, both are the same style of navigational menu.

The first example menu is created with CSS. The second is created with JavaScript.

It’s pretty easy to understand how you could create a menu like that with JavaScript. After all, JavaScript is a programming language, and programming languages can make decisions and do things. The decision for a drop-down menu goes something like, “if the user hovers over the square labeled ‘Two’, then display the drop-down; if the user stops hovering over any part of the menu, then stop displaying the drop-down.”

But if you recall, CSS is a markup language. It doesn’t make decisions and it doesn’t do stuff, it just styles HTML. So how exactly is it possible to make those decisions using CSS, and why am I saying it’s preferable to do so?

To answer the first question, I’m going to delve a bit more into how CSS works. Don’t worry; I’ll make it easy.

The basic structure of CSS is a bunch of commands that look like this:
property: value;
For example, take the statement “color: blue”. Color is a property which tells the computer what color a piece of text should be. It has a huge range of possible values. Blue is the specific value of the color property that we want to use in this circumstance.

A lot of the time, CSS properties don’t have such obvious names. For example, what do you think “margin: auto” does? It’s not obvious by reading the property name, so the programmer needs to know by rote. (Which this programmer does. “margin: auto” centers something.) So, the process of coding CSS is essentially translating between what you want the computer to do, and what properties you should set to what values to make that happen.

For purposes of creating drop-down menus with CSS, the single most important property is “display”, and the most important value of that property is “none”. Basically, “display: none” removes something entirely from the page. It’s like a CSS backspace key.

This “backspace key” is really useful for doing things like removing a drop-down menu from the screen when the user stops hovering over it.

So if that’s the “then” part of the statement “if the user stops hovering over any part of the menu, then stop displaying the drop-down”, how do we code the “if” part? How can we tell whether or not the user is hovering over the menu?

Fortunately for us, the part of the computer that figures out whether or not the user is hovering over the menu is not programmed in either JavaScript or CSS. It’s built into the web browser itself. So, both languages have the capability to figure that out. In JavaScript, it goes
if (!event.target.matches('.nav'))
In CSS, it goes
.nav a:not(:first-of-type) { display: none; }
Don’t worry about not understanding those code snippets, I just wanted to show them to you to demonstrate how different the same basic code looks in different languages.

So, we’ve got both pieces. We’ve got the decision, and we’ve got the action. And so, we can program drop-down menus with CSS, even though it’s not technically a programming language. Pretty cool, eh?

Now, I did previously say that not only is programming menus with CSS possible, it’s actually preferable. There’s one simple reason for this: ubiquity.

An unfortunate fact of life for web designers is that not everyone is going to be seeing your website in the same way. Their screen size could be bigger or smaller, or have different proportions. Their browser could be different from the one you use, or it could even be text-only. They may have some extensions enabled that you’ve never heard of, and they may not have extensions enabled that you use daily. And every one of these differences affects how that user will view your website. If your website isn’t usable to everyone on every device with every setting, you’ll drive away a ton of potential customers.

I bring this up because JavaScript is actually one of those potential differences between you and your users. There are a lot of people who don’t have JavaScript enabled. If you program your website’s navigation using JavaScript, your website will be completely unusable to someone who doesn’t have it enabled.

Nobody wants to disable CSS, however: while JavaScript is frequently used to make pop-ups and ads visible, and otherwise isn’t used for integral functions; disabling CSS would not prevent ads from being displayed and is one of the most integral parts of a webpage.

So, CSS is ubiquitous whereas JavaScript is not, and a crucial piece of your website should not be created with a non-ubiquitous language. That is the reason that I recently deleted all the JavaScript code I had for my website navigation and decided to start over with CSS. And that is the reason that you should program your menus with CSS instead of JavaScript.

How to Write CSS That Doesn’t Suck

A few days back, I read an article that ended up significantly improving the way I wrote CSS. Given how quickly and easily stylesheets can get horribly disorganized and out of hand, I found the tips to be immensely useful.

The article is primarily for teams of coders, who need to keep a ton of CSS organized such that many different people can understand it. Even so, I found a lot of it useful as an independent developer. Here are the things I found most useful:

  • Group related styles together. If you do absolutely nothing else this article mentions, do this. It is so helpful to scroll through a stylesheet and know that since you’ve run across your <p> tag styles, your <h1> styles have got to be around here somewhere.
  • After you’ve grouped related styles, try to arrange them by which page or set of pages they apply to. After that, create some suitably humungous, obnoxious, and obvious comment headers and make section headings, like this:
    /********************\
    ** ABOUT PAGE STYLES**
    \********************/
    This makes it infinitely easier to know which page you’re styling and also helps save your ass if you accidentally name a class or id something stupid and uninformative.
  • Make constructive use of white space. For closely-related styles, put only one blank line between styles; for more loosely-related styles, use 2 or 3. Put 4 blank lines before a new heading. This groups stuff up visually and makes it even easier to find what you’re looking for.
  • In terms of individual styles, use this standard format. It’s easy to read, it’s the near-universal standard, and more. Single-line CSS is almost never a good idea.
    .foo {
      display: block;
      background-color: green;
      color: red;
    }
  •  Indent full rule sets if they’re nested. For example, if you’re mobile enabling, indent all the styles inside the brackets after the @media tag.
  • If a style relies on another style elsewhere, or if the meaning of the styles is otherwise at all ambiguous, add a comment! CSS never has enough comments. I know it’s annoying that there’s no single-line comment, but seriously, you can afford to type that extra asterisk and slash to make your code readable.
  • Last tip: be very, very literal about your selectors, because the computer certainly will be. Do not say “header ul” when you mean “.nav”; even if you don’t have another ul in your header, this kind of selector generality is a very bad habit that can and will come back to bite you. Whenever you’re writing a selector, ask yourself: “do I want ALL x, or just some x?” If you want just some x, write a more specific selector. Even if you don’t think you’ll ever use the other types of x.

If you want more CSS tips, go on and read the full article! It’s a fun and helpful read, full of great info. Otherwise, that’s all for today: happy coding!