Wednesday, February 24, 2021

30 CSS Best Practices for Beginners

30 CSS Best Practices for Beginners

CSS is a language that is used by nearly every developer at some point. While it's a language that we sometimes take for granted, it is powerful and has many nuances that can help (or hurt) our designs. Here are thirty of the best CSS practices that will keep you writing solid CSS and avoiding some costly mistakes.

1. Make it Readable

The readability of your CSS is incredibly important, though most people overlook why it's important. Great readability of your CSS makes it much easier to maintain in the future, as you'll be able to find elements quicker. Also, you'll never know who might need to look at your code later on.

2. Keep it Consistent

Along the lines of keeping your code readable is making sure that the CSS is consistent. You should start to develop your own "sub-language" of CSS that allows you to quickly name things. There are certain classes that I create in nearly every theme, and I use the same name each time. For example, I use .caption-right to float images which contain a caption to the right.

Think about things like whether or not you'll use underscores or dashes in your ID's and class names, and in what cases you'll use them. When you start creating your own standards for CSS, you'll become much more proficient.

3. Start with a Framework

Some design purists scoff at the thought of using a CSS framework with each design, but I believe that if someone else has taken the time to maintain a tool that speeds up production, why reinvent the wheel? I know frameworks shouldn't be used in every instance, but most of the time they can help.

Many designers have their own framework that they have created over time, and that's a great idea too. It helps keep consistency within the projects.

At the same time, I would also like to say that you should use frameworks only if you already know a good deal of CSS. There will almost certainly come a time when you will have to create a certain aspect of some layout all by yourself and your deep understanding of CSS will help you get things done.

4. Use a Reset

Most CSS frameworks have a reset built-in, but if you're not going to use one then at least consider using a reset. Resets essentially eliminate browser inconsistencies such as heights, font sizes, margins, and headings. The reset allows your layout look consistent in all browsers.

The MeyerWeb is a classic reset. Normalize.css is another very popular reset.

5. Organize the Stylesheet With a Top-Down Structure

It always makes sense to lay your stylesheet out in a way that allows you to quickly find parts of your code. I recommend a top-down format that tackles styles as they appear in the source code. So, an example stylesheet might be ordered like this:

  1. Generic classes (bodyaph1, etc.)
  2. #header
  3. #nav-menu
  4. #main-content

It also helps if you keep track of different section of the website in the stylesheet with comments.

6. Combine Elements

Elements in a stylesheet sometimes share properties. Instead of re-writing previous code, why not just combine them? For example, your h1h2, and h3 elements might all share the same font and color:

We could add unique characteristics to each of these header styles if we wanted (ie. h1 {size: 2.1em}) later in the stylesheet.

7. Create Your HTML First

Many designers create their CSS at the same time they create the HTML. It seems logical to create both at the same time, but actually you'll save even more time if you create the entire HTML mockup first. The reasoning behind this method is that you know all the elements of your site layout, but you don't know what CSS you'll need with your design. Creating the HTML layout first allows you to visualize the entire page as a whole, and allows you to think of your CSS in a more holistic, top-down manner.

8. Use Multiple Classes

Sometimes it's beneficial to add multiple classes to an element. Let's say that you have a div "box" that you want to float right, and you've already got a class .right in your CSS that floats everything to the right. You can simply add an extra class in the declaration, like so:

You can add as many classes as you'd like (space separated) to any declaration.

This is one of those situations where you have to take individual cases into account. While it is helpful to create class names that provide some hint of how they affect the layout, you should also avoid using class names that require you to constantly switch between HTML and CSS.

Be very careful when using ids and class-names like "left" and "right." I will use them, but only for things such as examples in blog posts. How come? Let's imagine that, down the road, you decide that you'd rather see the box floated to the left. In this case, you'd have to return to your HTML and change the class name—all in order to adjust the presentation of the page. This is unsemantic. Remember: HTML is for markup and content. CSS is for presentation.

If you must return to your HTML to change the presentation (or styling) of the page, you're doing it wrong!

9. Use the Right Doctype

The doctype declaration matters a whole lot on whether or not your markup and CSS will validate. In fact, the entire look and feel of your site can change greatly depending on the doctype that you declare.

Learn more about which doctype to use at A List Apart. You can simply start using <!DOCTYPE html> when creating pages based on HTML5.

10. Use Shorthand

You can shrink your code considerably by using shorthand when crafting your CSS. For elements like padding, margin, font and some others, you can combine styles in one line. For example, a div might have these styles:

You could combine those styles in one line, like so:

If you need more help, here's a comprehensive guide on CSS shorthand properties.

11. Comment your CSS

Just like any other language, it's a great idea to comment your code in sections. To add a comment, simply add /* behind the comment, and */ to close it, like so:

12. Understand the Difference Between Block and Inline Elements

Block elements are elements that naturally clear each line after they're declared, spanning the whole width of the available space. Inline elements take only as much space as they need, and don't force a new line after they're used.

Here are the lists of elements that are typically inline:

And the block elements:

13. Alphabetize your Properties

While this is more of a frivolous tip, it can come in handy for quick scanning.

This is a bit controversial because you have to sacrifice speed for slightly improved readabilityHowever, you should not hesitate in trying it out if you think it will help you.

14. Use CSS Compressors

CSS compressors help shrink CSS file size by removing line breaks, white spaces, and combining elements. This combination can greatly reduce the the file size, which speeds up browser loading. CSS Optimizer and HTML Compressor are two excellent online tools that can shrink CSS.

It should be noted that shrinking your CSS can provide gains in performance, but you lose some of the readability of your CSS.

15. Make Use of Generic Classes

You'll find that there are certain styles that you're applying over and over. Instead of adding that particular style to each ID, you can create generic classes and add them to the IDs or other CSS classes (using tip #8).

For example, I find myself using float:right and float:left over an over in my designs. So I simply add the classes .left and .right to my stylesheet, and reference it in the elements.

This way you don't have to constantly add float:left to all the elements that need to be floated.

16. Use margin: 0 auto to Center Layouts

Many beginners to CSS can't figure out why you can't simply use float: center to achieve that centered effect on block-level elements. If only it were that easy! Unfortunately, you'll need to use

to center a div, paragraphs or other elements in your layout.

By declaring that both the left AND the right margins of an element must be identical, the browsers have no choice but to center the element within its containing element.

17. Don't Just Wrap a div Around It

When starting out, there's a temptation to wrap a div with an ID or class around an element and create a style for it.

Sometimes it might seem easier to just create unique element styles like the above example, but you'll start to clutter your stylesheet. This would have worked just fine:

Then you can easily add a style to the h1 instead of a parent div.

18. Use Browser Developer Tools

Modern web browsers come bundled with some vital tools that are must haves for any web developer. These developer tools are now part of all the major browsers, including Chrome, Firefox, Safari and Edge. Among the many features that come bundled with the Chrome and Firefox developer tools (like debugging JavaScript, inspecting HTML, and viewing errors), you can also visually inspect, modify, and edit CSS in real-time.

19. Hack Less

Avoid using browser-specific hacks if at all possible. There is a tremendous pressure to make sure that designs look consistent across all browsers, but using hacks only makes your designs harder to maintain in the future. Plus, using a reset file (see #4) can eliminate nearly all of the rendering irregularities between browsers.

20. Use Absolute Positioning Sparingly

Absolute positioning is a handy aspect of CSS that allows you to define where exactly an element should be positioned on a page to the exact pixel. However, because of absolute positioning's disregard for other elements on the page, the layouts can get quite hairy if there are multiple absolutely positioned elements running around the layout.

21. Use Text-transform

text-transform is a highly-useful CSS property that allows you to "standardize" how text is formatted on your site. For example, say you're wanting to create some headers that only have lowercase letters. Just add the text-transform property to the header style like so:

Now all of the letters in the header will be lowercase by default. text-transform allows you to modify your text (first letter capitalized, all letters capitalized, or all lowercase) with a simple property.

22. Don't Use Negative Margins to Hide Your h1

Oftentimes people will use an image for their header text, and then either use display:none or a negative margin to float the h1 off the page. Matt Cutts, then head of Google's Webspam team, has officially said that this is a bad idea, as Google might think it's spam.

As Mr. Cutts explicitly says, avoid hiding your logo's text with CSS. Just use the alt tag. While many claim that you can still use CSS to hide a h1 tag as long as the h1 is the same as the logo text, I prefer to err on the safe side.

23. Validate Your CSS and XHTML

Validating your CSS and XHTML does more than give a sense of pride: it helps you quickly spot errors in your code. If you're working on a design and for some reason things just aren't looking right, try running the markup and CSS validator and see what errors pop up. Usually you'll find that you forgot to close a div somewhere, or a missed semi-colon in a CSS property.

24. Rems and Ems vs. Pixels

There's always been a strong debate as to whether it's better to use pixels (px) or ems and rems when defining font sizes. Pixels are a more static way to define font sizes, and ems are more scalable with different browser sizes and mobile devices. With the advent of many different types of web browsing (laptop, mobile, etc.), ems and rems are increasingly becoming the default for font size measurements as they allow the greatest form of flexibility.

25. Don't Underestimate the List

Lists are a great way to present data in a structured format that's easy to modify the style. Thanks to the display property, you don't have to just use the list as a text attribute. Lists are also great for creating navigation menus and things of the sort.

Many beginners use divs to make each element in the list because they don't understand how to properly use lists. It's well worth the effort to use brush up on learning list elements to structure data in the future.

26. Avoid Extra Selectors

It's easy to unknowingly add extra selectors to our CSS that clutters the stylesheet. One common example of adding extra selectors is with lists.

In this instance, just the .someclass li would have worked just fine.

Adding extra selectors won't bring Armageddon or anything of the sort, but they do keep your CSS from being as simple and clean as possible.

27. Add Margins and Padding to All

Modern browsers are fairly uniform in the way they render elements, but legacy browsers tend to render elements differently. For example, Internet Explorer renders certain elements differently than Firefox or Chrome, and different versions of Internet Explorer render differently from one another.

One of the main differences between versions of older browsers is how padding and margins are rendered. If you're not already using a reset, you might want to define the margin and padding for all elements on the page, to be on the safe side. You can do this quickly with a global reset, like so:

Now all elements have a padding and margin of 0, unless defined by another style in the stylesheet.

28. Use Multiple Stylesheets

Depending on the complexity of the design and the size of the site, it's sometimes easier to make smaller, multiple stylesheets instead of one giant stylesheet. Aside from it being easier for the designer to manage, multiple stylesheets allow you to leave out CSS on certain pages that don't need them.

For example, I might having a polling program that would have a unique set of styles. Instead of including the poll styles to the main stylesheet, I could just create a poll.css and the stylesheet only to the pages that show the poll.

However, be sure to consider the number of HTTP requests that are being made. Many designers prefer to develop with multiple stylesheets, and then combine them into one file. This reduces the number of HTTP requests to one. Also, the entire file will be cached on the user's computer.

29. Check for Closed Elements First When Debugging

If you're noticing that your design looks a tad wonky, there's a good chance it's because you've left off a closing </div>. You can use the XHTML validator to help sniff out all sorts of errors like this.

30. Try to Use Flexbox and Grid Layout Instead of Floats

In the past, it was very common and necessary to use floats to create any kind of layout. Unfortunately, floats come with a lot of problems. You can instead start using the much more powerful layout modules called flexbox and grid layout. Flexbox will help you create one dimensional layout and grid will help you with two dimensional layouts.

31. Use !important Sparingly

The keyword !important is used to bypass any styling rules specified elsewhere for an element. This allows you to use less specific selectors to change the appearance of an element. As a beginner, this might seem like an easy way to style elements without worrying about what selectors you should be using. However, you should avoid that as using !important with a lot of elements will ultimately result in !important losing its meaning as every CSS rule will now bypass the selector specificity.

One possible use for !important is to specify the style of third-party elements added to a webpage where you cannot alter the original stylesheet or its loading order etc.

You Might Also Enjoy...

This post has been updated with contributions from Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials, and to learn about new JavaScript libraries.


No comments:

Post a Comment