If I had a penny for every time I went back into some code that I had written and couldn’t figure out what the heck I was trying to do, I’d be quite the wealthy man at this point. It’s important that you comment your code properly so that when you need to come back to it, you can quickly find your way around and change what you need to. When your site starts to grow, so does the amount of styling needed. With so many different selectors, declarations and values, learning to comment your code is an valuable tool. Today, we’ll go through just that and show you how and where (in my opinion) you should comment your CSS. Keep in mind, this is purely opinionated. As you grow as a developer, you’ll find your own style of how and where you like to write your comments. With no further delay, let’s dive in.

PART ONE:

Comment Syntax

The CSS comment syntax is extremely simple. When you want to start a comment, you begin with a forward slash and and asterisk (/*). To end your comment, you use an asterisk first and then another forward slash (*/). Here’s what a few typical CSS comments might look like:

None of the lines above will be interpreted by the browser, so it’s not going to break your code. Usually, if you’re using more than just a plain text editor, your comments will appear a different color making them even easier to read.

PART TWO:

Purely Opinionated

When I write my CSS, I typically like to use comments to break up different sections. Again, this is purely based on my own preference, and there are several ways to organize your CSS. If I’m not mistaken, there are even programs that will organize it for you. Anyhow, take the following CSS into consideration:

As you can see, each section of my “page” is broken down via CSS comments. This is typically how I write my CSS code. Another form of comments that may come in handy is comments that are placed directly next to a specific value in order to denote something important about it. Let’s use the previous CSS as an example. Notice the new comment in the footer section that tells you more about that particular element:

So now, when you go back and look at this code, you have some type of organization to it. You also have extra comments to help determine important features of a specific element. It doesn’t get much better than that!

Again, I cannot stress to you the importance of commenting your code. Imagine a CSS file with over 1000 lines of code (yes, they grow this large and even larger) with no comments. It would be a horrific task to have to go back and find the element that you need to change, so keeping things organized will save you tons of headaches in the future. Join us next time when we look into CSS positioning and how it works. See you then!

Download Source Files