25 Expert Tips for Cleaner CSS Coding for WordPress
There are many benefits to having clean, organized CSS: lightweight code – and, as a result, a lightweight file size – helps your website load more quickly, it’s easier to read, quick to search through when you want to make updates or troubleshoot problems and, above all, serves as testament to your professionalism as a developer.
Learning how to write well-crafted code is an essential skill when you’re working with WordPress and want to make style changes to your website. And if you want to ensure your code is tight and efficient, there are some principles you need to keep in mind.
The tips below will help you level up your CSS knowledge and write clutter-free and optimized CSS, making you a better all-around WordPress developer.
1. Figure Out Your Layout
First thing’s first: you should plan your layout because doing it at this stage will ensure there’s less room for redundancy. Plus, if you take the time to plan now, you can choose the styles you need and none of the extra stuff that ultimately contributes to a messy, bloated stylesheet.
While this step is the first in this post, you will actually get a better idea of what planning your layout entails when you’re read the whole article through. But in essence, your goal for this step is to create a table of contents of all the IDs and classes you expect to use. After your structure is decided, you can go ahead and code your way through it.
2. Code with Future Reviewers in Mind
D. Keith Robinson was onto something when he wrote in “Tips for a Better Design Review Process” that you should keep in mind who might see your code when you set out to write it. This is especially important if you’re planning to submit your theme or plugin to WordPress.org since it’s likely many other people review, edit, debug or build upon your creation.
Keeping things neat and tidy helps speed up future development for you or anyone else who may look at your code.
3. Write a Table of Contents
Once you have planned out the structure of your stylesheet, it’s a good idea to help keep things organized by creating a table of contents at the top of the file. You can achieve this by simply writing each section as a multi-line comment.
Here’s an example of a table of contents using a multi-line comment to help keep your styles organized:
Realistically, you don’t have to make it look that flashy, but at the same time all the extra characters help draw your eye to the title so anyone who reviews your stylesheet won’t miss it. Every developer has a different approach to this, so there’s really no “right” way. There’s only the way you prefer.
You could simply follow Automattic’s lead and adopt their style for official WordPress themes:
If all WordPress theme developers adopted this style, it would certainly make life easier since developers would be sharing the same standard.
Plus, this example uses less characters than the previous one, which saves a little space. Sure, it may only be a few bits and bytes, but these things add up quickly and saving space where ever you can helps in the long run.
No matter which method you choose, a table of contents can help remind you of where you placed everything, so future updates and troubleshooting become easier. You won’t need to look through thousands of lines of code – one-by-one – to find the one line you need to edit. You can just scroll to that section and look through a much smaller selection of code.
4. Write Descriptive IDs and Classes
When you’re writing CSS, it can be tempting to breeze through it without thinking about the future. It’s easier to come up with IDs and classes that seem to fit in the moment rather than thinking about how your thought process may differ later on. You may name IDs and classes that make sense to you now only to be confused later on after forgetting your earlier thought processes.
That’s why it’s important to think of names for your IDs and classes that are broad enough to be clear and easy enough to understand, while also being specific enough to distinguish between different elements of your CSS.
It sounds like a difficult task, but once you run through a few examples, it’s a snap. For instance, I see many developers using a ID of
#container or something similar for the main content area which would be too broad since a container could be used for just about anything. If not that, I see IDs that are way too specific such as
#leftcontainermain which is not only a mouth full, but difficult to read.
Instead, try using
#content or if you have many different content areas, try
5. Don’t Use Position-Specific Names
One of the mistakes I see frequently when looking under the hood of themes and plugins is the use of IDs and classes that are named for their design or position. For example,
While this isn’t actually a mistake and there’s nothing inherently wrong with using this naming system, it does pose a problem for future development. If you’re looking at your screen and scrunching your face in confusion or possibly outrage, let me explain.
What if later on, you decide you want to make a minor tweak to that left-positioned container or blue font? It’s not such a big deal until you make so many updates and changes that your
#left-container is no longer on the left and your
#blue-font is green and maybe even includes some link styling that you added on the fly.
Going through and updating that code again or trying to troubleshoot might not be difficult for you if you remember the changes you made, but it’s a nightmare for anyone trying to use, edit or build upon your styles.
The alternative is to take out position and design from your IDs and classes. When in doubt, it’s much clearer to stick with names that are after your layout like
#footer. It’s much more concise for everyone.
6. Create Sections with IDs
An even more efficient way to name your sections in your table of contents is to turn them into IDs. That way, it’s even easier to recognize each segment of your stylesheet for easier reviewing and troubleshooting.
If you were to use Automattic’s table of contents style, but also included IDs, it would look something like this:
While this wouldn’t be the only section you likely should include, it gives you an idea of how you could structure your stylesheet for ultimate clarity.
7. Label Sections with Comments
When you arrive to a section of your stylesheet, first write a comment that includes the name of the section and a short description of what’s included. This makes your CSS easier to navigate and understand.
If you’re following along so far, you already named your sections for your layout using corresponding ID and class names. You may also be following the lead of Automattic and adopting their structure for your table of contents.
With all this in mind, here’s an example of how you can declare your sections loudly and proudly to add even more clarity to your stylesheet:
8. Use the Search Feature
Want your sections to be even easier to find? One of the most valuable tools I love to use for updates and troubleshooting is using my script editor or browser’s search feature. I can search for the title of a section found in the table of contents, then jump right to each part of the document where it’s referenced, one at a time.
In Google Chrome, for example, when I’m looking at a theme’s stylesheet directly in my dashboard, I can press Ctrl + F on my Windows keyboard or Command + F for Mac OS X. An inline pop-up appears in the top corner where I can enter a search term to find all instances of it on the page.
It’s a valuable tool that can save you a lot of time.
9. Create Flags for Your Sections
Douglas Bowman has a great tip for making searches through your stylesheet that much more efficient: Use flags in your section titles. Why? Searches within a document for an ID you use for your section titles along with multiple other places all turn up in the results. You still need to sift through all those instances.
Using flags for your sections means you can search for the title of a section that includes the flag and you only turn up one result. It also happens to be the only and exact result you need, saving you even more time.
A flag in this case would be a character that isn’t otherwise used in CSS syntax.
What does this look like in action? Here’s an example of how you can write a flag for your sections using the same tips already listed:
This is the same example used in the previous tip, but with one addition. I included an
= symbol directly in front of the title.
Now when anyone wants to search for the style in the header section, they can search for
=#header and only the title for the section will turn up in the results. Now there’s no need to sift through tons of results.
10. Write a Comment for the Flags
What’s the point including a flag in your titles if you don’t let everyone know you included it? Probably not much point at all.
In your table of contents, don’t forget to add a quick note about the flags you use in your section titles as a reminder to yourself and also to let anyone who reviews your stylesheet know there’s an easy way to search your file.
11. Separate Layout from Design
CSS can not only add styling elements to your site or plugin’s design like colors, images and backgrounds, but it can also design much of your layout. With that in mind, if you don’t separate your design and styles from your layout, your stylesheet can quickly become messy and difficult to read.
Coding your layout styles first, followed by your design styles keeps things more organized. How you do this depends on the particular project you’re working on, but you could either write this order for each section or you could write a separate section for your layout altogether.
12. Write Comments for Clarity
Adding comments is one of the best ways to ensure your CSS is easy to understand. Anywhere you think a certain styling may need to be explained for easy editing or to avoid a catastrophe, add a comment whether it’s on the same line as a declaration or directly before it.
This helps keep someone from erasing or editing a line or section improperly, especially when it could break the layout, for example.
13. Keep a Reference List Handy
It may be helpful for you to record the entire structure of your stylesheet for your records, kind of like an enhanced table of contents. It can help you stay on track while you’re coding and also provide you with reminders later on when you need to update the file or troubleshoot.
While you’re at it, why not keep a list of your favorite resources handy? Instead of trying to remember every property and value known to man, keep a list of that stuff bookmarked so you don’t have to wrack your brain trying to figure out how to accomplish something with CSS.
If you’re in need of a handy and complete list of resources, check out A Mega Guide for Learning and Referencing CSS for WordPress: 150+ Resources.
14. Create a CSS Library
Arguably even handier than a resource or reference list is your own CSS library. It’s a resource of all the constant elements you used to put your stylesheet together such as the templates, documentation, pre-written code, dummy content, common IDs and classes, and the like.
They’re convenient for not only troubleshooting but also for reusing for future projects so you don’t have to start from scratch.
To create one, you can set up a few pages on your site for your personal or public reference as you see fit or create a repository on GitHub. You could also just save a copy for yourself on your computer.
How you save your code library is all up to you.
15. Order Properties Alphabetically
Christian Montoya had the right idea when he mentioned this tip in his post CSS Techniques I Use All the Time. It organizes your properties so it’s much easier to find.
Here’s Montoya’s example of how this could work in your stylesheet:
16. Choose Your Divisions Wisely
div tags you add to your site that need their own CSS styling, the more you risk structural bloating. The solution is to use only the amount of divisions you really need. Try to think of other ways you can achieve the same layout and design without using yet another
This is also where keeping a list of resources and references nearby is especially helpful.
17. Use Proper Spacing
This seems like an obvious tip at first glance, but it’s a bit more complicated than you might think. If you use proper spacing between all your selectors and declarations such as in the example below, it certainly helps keep things clear and easy to read, but there’s a downside.
Every space you type adds to the overall file size. It may not seem like much, but every byte counts and adds up in the end. If you can get away with conveniently forgetting to type a space between the selector and bracket or the colon and value on a regular basis, it wouldn’t be a horrible thing.
You may think it doesn’t save that much space or time and it doesn’t really, on its own, anyway. If you implement all the tips listed here, it can all add up to be quite a bit.
18. Use Section Breaks
It may seem simple, but it’s definitely worth mentioning since it’s an important tip.
Adding a section break between styles, selectors, sections and table of contents makes for a really well-organized stylesheet. It can also help your stylesheet to be easy to read, especially if you decide to omit spaces elsewhere.
Take the Twenty Sixteen stylesheet, for example:
Adding section breaks after selectors can definitely make your code super easy to read and find what you need to edit.
19. Don’t Use Too Many Selectors
As a general rule of thumb, if you don’t need to type a selector, then don’t. Keeping your selectors to a minimum means your stylesheet is easier to read and it should be easier to identify what you need to edit when troubleshooting.
If you clearly mark your sections, you won’t need to include your those selectors with other ones such as in the example below:
In the above code, the #sidebar selector wouldn’t be necessary. Removing extra selectors can also help save a few bytes here and there.
20. Don’t Use Unnecessary Hacks
Employing CSS hacks can be an effective way to fix styling that doesn’t work for your needs, especially if you need it to compensate for a bug. But the truth is, hacks can really make it difficult to change things later on.
If you find a bug, notify the theme or plugin developer first to see if they’re planning on fixing it before adding in your own CSS hack. If you think you still need to add one temporarily, be sure to make a note of it for your records and add a comment next to the line containing the hack to remind yourself why you put it there.
Adding too many hacks to your stylesheet can not only be confusing when you’re changing things around, but you also run the risk of ruining your layout and design if your hack isn’t compatible with the changes you want to make so be sure to think of the repercussions beforehand and try to find an alternative whenever possible.
21. Keep the Important Tag to a Minimum
!important tag is an effective way to make sure new styles you type take precedent over other styles that are otherwise dominant, but you should only use it if it’s absolutely necessary.
If you’re throwing this tag around like you’re giving away candy to children, it results in a messy stylesheet that could be difficult to edit in the future. You could end up trying to furiously edit a declaration that just won’t take. You’ll then have to spend a lot of time tracking down all the !important tags you have lying around. In effect, it takes you double the time to make a simple change. That’s not only frustrating for you but also frustrating for anyone trying to edit or build upon your theme or plugin to suit their needs.
Sometimes you just can’t get around it and that’s fine, but you shouldn’t be okay with seeing it all the time in a stylesheet, either.
22. Use UFT-8
The UFT-8 character code is a universal one and using it in most cases helps solve a lot of future compatibility issues. Of course, you won’t always be able to use it, for example, if you need to employ translations with characters that aren’t included in UFT-8, but if you can get away with it, use the latter.
23. Use the
em Unit for Text
CSS-Tricks has a great article on the em unit and why you should use it. This unit sizes text relative to the original sizing that’s set. If you use pixels to size your text, it may look great on your browser, but not so much on other devices like mobile screens.
According to comScore, the activity on smartphones and tablets accounts for 60% of the total time spent on media devices in the US. Since so many people use screens other than their desktop to view sites across the web, it makes sense to make the viewing experience as pleasant as possible for them.
em unit ensures your text automatically resizes itself to display well across all platforms.
24. Use a Separate ID for Anchors
Anchor links naturally take on the same styling as active and hover value links. In many cases, you may want anchors to look and act differently than regular ol’ links. If this is the case, using a separate ID for anchors can help you achieve it.
It’s a much more organized way to style anchors as opposed to using an
!important tag, for example. It also makes it easier and faster to make changes in the future. You’re welcome.
25. Don’t Use the
It may seem like an effective way to fix the differences across browsers between margins and paddings, but the
* selector makes it more difficult for your browser to load your page, meaning your site could load a lot slower than you intended, especially if you have a large site.
On top of which, it could also interfere with default styling that you actually want to keep which means your site might not look exactly like you had hoped. This being the case, not using this selector could save you quite a bit of time troubleshooting your design, not to mention it slows down your site’s response time.
You’re better off addressing browser compatibility in a separate section of your stylesheet, typically, at the beginning.
Writing cleaner CSS code doesn’t have to be an insurmountable task. If you use many or all of these tips, you would be well on your way to coding better WordPress stylesheets.
For more tips to stay ahead of the game and up-to-date on your CSS skills, check out some of our other posts: Understanding CSS Grids for Modern WordPress Website Design and Using CSS Media Queries for a Responsive WordPress Design.Tags: