14 CSS Best Practices for the Beginner

Jul 25, 2022
A lady reading a book about css best practices

Today, we'll review 14 CSS most effective practices for beginners However, even experts need to brush up on fundamentals at times.

1. Organize the Stylesheet

Your initial task in applying CSS most effective practices is to organize your stylesheets. How you approach the process will be contingent on the work, but as a general guideline, it is recommended to adhere to the following organization principles:

Be Consistent

Whichever way you decide to arrange your CSS be sure to make your decisions constant across your entire stylesheet as well as throughout your website.

From naming classes to comments to line indents to comment structures, keeping the same structure will allow to track your work more easily. Furthermore, it makes sure that the making of changes later, is headache-free.

Make use of Line Breaks in a variety of ways

Although CSS works even if it's visually ugly but it's more beneficial to you as well as for others working with your code if you use plenty of line breaks to keep each code snippet distinct and legible.

Typically, it's best to put each value and property pair in the separate line.

Screenshot of CSS code from Mozilla.org, showing the legibility of CSS when structured so properties and value pairs exist on their own lines.
CSS code

Create New Sections Where it is logical

The way you structure your stylesheets is contingent on the type of site you're creating. However, as a principle, it's a good idea to set up sections for styles as they'll be used. So, a section for types of text, a section for columns and lists, and sections for navigation as well as links, and so forth. It is also possible to create sections specifically for pages that may have different styling than the rest like the FAQ or store.

Comment Your Code

Although you may not never see your CSS, it's still an excellent idea to make sure you are thorough in your comments. Comments will look like the following:

/* This is the way a normal CSS comment appears like.(or

It is easier for you to figure out what each section is in relation to quickly without having to pore over every line in the future.

Comments are a great way to identify sections, but you could also use them to provide insights as to the decisions you've made - especially if it's possible to not remember later.

Use Separate Stylesheets for Larger Projects

This won't apply to every website, but if you have a large website that requires a lot of specific CSS and stylesheets, having multiple styles is a good strategy. No one - including yours - has to search for an extremely long time to find one line of code you need.

Avoid the hassle and create separate stylesheets for different site sections, particularly if they have completely different styles.

2. Inline CSS vs. External CSS and. Internal CSS

There are three kinds of CSS that you could require to be aware of while creating your website and adjusting its styling. Let's discuss what each is and does before deciding which need to be using in the projects you are working on.

  • Inline CSS. It lets you design specific HTML elements,
  • Internal CSS. This allows you to design the entire webpage instead of particular elements.

Many developers recommend avoiding the use of inline CSS at all, as it usually can't be cached in the first place, and is recommended to not split CSS across multiple files. In the simplest case, it should be used sparingly.

It is only possible to see an need for it in the event that it's the styling of one particular section, piece of text, or area of a single page of your website. This is probably the only scenario where inline CSS is a workable solution.

Other than that the use of external CSS, or internal CSS, based on your needs, are the most efficient options since they can help you save time and time. Decide on the styles one time, and then use them on your site. Then, boom - you're done.

3. Minify Your Stylesheet

Adjusting code minification settings in  CDN.
Setting the minification of code settings for CDN.

It allows you to alter the minification of code for your entire site.

4. Utilize a Preprocessor

This means that the pre-processor acts as the pre-processor "CSS + "where it includes a couple of additional features that typically don't occur in CSS alone. The addition of these features typically makes the output CSS clearer and simpler to use.

It is necessary to install a CSS compiler for your site's server for the use of preprocessors. A few of the most well-known pre-processors are Sass, LESS and Stylus.

Screenshot of the Sass homepage.
Sass

5. Think about the possibility of a CSS Framework

Frameworks allow you to quickly deploy large projects as well as avoid the possibility of problems. And they provide the benefit of standardization, which is crucial when a number of people are working on an initiative simultaneously.

Everybody will use the same name-naming procedure as well as the same layout options, the same commenting procedures, and so forth.

However they can also lead to generic-looking websites and much of the code could become unusable.

Screenshot of the Bootstrap homepage.
Bootstrap

6. Start with a Reset

One thing you can quickly apply is to begin developing using the use of a CSS reset. Using something like normalize.css can make the browsers all render elements of your website consistently using the most current standards to minimize browser inconsistencies.

This reset is actually a small CSS file you can put on your website in order for a better quality of cross-browser compatibility to the design of HTML elements and serves as an improved method to carry out the CSS reset.

7. Classes are different from. IDs

The next thing you should pay attention to while following CSS best practices is how you treat classes and IDs. In case you're not familiar, let's define both briefly:

  • Class. The class selector operates by selecting an element with an attribute class. The class attribute determines how the HTML element is chosen. It looks like this in code: .classname
  • ID. ID, on contrary, operates by selecting elements that have the ID attribute. It is important to note that the ID attribute must match the value used by the selector to function. You can spot an ID in CSS using the symbol #.

As we discussed in our discussion of internal CSS vs external CSS earlier You use IDs to apply a style on a single element. The idea behind IDs is to be used for styling the exceptions within the webpage, and not to create overarching styles that would apply to the entire page or site.

8. Avoid Redundancy

One of the CSS best practices to follow is to eliminate redundant work whenever you can. Below are some basic guidelines you can follow in order to implement this technique into your work flow:

Make use of the Dry method

The DRY method refers to "Don't repeat Yourself" and is basically the notion that you should never repeat code in CSS. It's a waste of time and tedious to input these styles manually every time, however at worst it can actively slow down your website.

A good idea is to go through your code for redundancies. Tags aren't required to identify font size twice in the same section such as. Eliminate the repetitions, so that your code reads better and work better as well.

Utilize CSS Shorthand

CSS shorthand can be a fantastic option to minimize the space that the code occupies and still function exactly as it is supposed to. You can combine multiple styles on the same line when it makes sense to do so. If, for instance, you're creating the style of a specific div, you can list the margin, padding, font, font size and even the color on a single line.

Are you interested in knowing how we increased our visitors by 1000 per cent?

Join the 20,000+ who receive our newsletter every week with insider WordPress advice!

Create Multiple Classes for Your Elements

When appropriate, you could also avoid redundancies by using multiple classes to an element. In the case of a webpage's content is floating towards the left due to class .left but you need to move a column on the page towards the right then you could add it to the element to prevent confusion. It also tells CSS specifically what element you'd like to float towards the left aboveof the usual left alignment.

The best thing is that you can create as many classes you like to an element provided it's separated by a space.

Combine Elements Where Possible

Instead of listing the elements in a single order, you can combine them to save space and also time. A lot of times, the elements inside the same stylesheet may be similar (or the same) styles. There's no need to list out the color, font, and alignment for each part of the text when they're all using the same design. Instead, combine them into one line, such as this:

H1, h2 and h3 p font-family: Ariel. Color: #00000

Do not use unnecessary selectors

Sometimes your code will be a little messy when you work on finalizing the design of your website. This is why it's important to go back and remove irrelevant selectors following the fact. Keep an eye out for overly complicated selectors as well. For instance, if you plan to design lists on your website there is no need to utilize selectors like "body" or "container" or something like that. Simply .classname {li Liwill suffice.

9. How Do I Properly Import Fonts

Using @font-face to Import Fonts

You are able to include almost any font you want to your website. However, you'll need to follow an exact procedure to be sure it works properly.

Screenshot of the Webfont Generator
Webfont Generator
  1. Download the font you are planning to use. There are many sites where you can get fonts, including Google and Adobe. You must download the TrueType Font file (.ttf) for your chosen font.
  2. Upload the customized font you'd like to use to this Webfont Generator that is made available through Font Squirrel. Download the Web Font Kit once it's produced. It will contain several files including several different font files with extensions like .ttf, .woff, .woff2 as well as .eot. Also, there should be an CSS file that is included.
  3. The HTML text editor you choose will do like NotePad and Sublime. Within this file, it has an "source URL" listed. You will need to update it to reflect the location the location where it is that the Web Font Kit is now stored on your web server. Copy the file path for the font files located on your host into this file according to the following format:
@font-face 
 font-family: "FontName";
 src: url("https://sitename.com/css/fonts/FontName.eot");
 src: url("https://sitename.com/css/fonts/FontName.woff") format("woff"),
 url("https://sitename.com/css/fonts/FontName.otf") format("opentype"),
 url("https://sitename.com/css/fonts/FontName.svg#filename") format("svg");
 

You can then put your new fonts to use by adding them to the site's CSS documents using an "font-family" tag.

Another thing you can do is limit the characters used in your customized fonts. If you're using only just a handful of characters from the font (for a header or logo, perhaps) you don't need to call the entire character set of characters, only the ones you require. In accordance with the new rules, to request just one character "Hello" you'd do this as follows:

Self-Hosting Fonts Whenever Possible

Be Careful with Font Variations

Font variations can be super useful for adding fun styles on your site. However, if not used properly, they may end down ruin your site, as well.

If you assign more than one style under font-variation-settings, it's likely they will overlap and one will override the other. It's better to keep things simple and employing font properties instead. illustrated here:

.bold 
 font-weight: bold;
 
 .italic 
 font-style: italic;
 

Utilize a Fallback Font

While you might put in the effort to add the custom font you want to use on your site and then use it through CSS but it's not 100% effective all the time, especially when accessed by someone using an outdated web browser. However, you want your users to enjoy a pleasant browsing experience.

To accommodate this you must create a fallback font which will be used in the event that none of your other fonts be acceptable. In order to do this, simply select the fallback font next to your preferred font when setting the family of fonts. This way you can ensure that the CSS will select your preferred font first. Then, your second choice, then the third choice then the fourth, etc.

  • Serif: Times New Roman, Georgia, Garamond
  • Sans-serif:Arial Tahoma Helvetica
  • Monospace: Courier New
  • Cursive Brush the script with MT
  • Fantasy: Copperplate, Papyrus

10. Create CSS accessible

Everybody should make their sites accessible, point blank. It's the same with your method of using CSS also. The goal is to make your website usable for as many people as possible and implementing accessibility features is an excellent way to accomplish this.

You can make your CSS available in a variety of ways:

  • Make pop-ups dismissable by pressing the ESC key. Those who use screen readers or magnification may not be able to see the "X" on the screen to dismiss a pop-up, therefore making them disengageable with a keystroke is essential.
  • Some devices won't even show pop-ups in the first place So make sure that all vital information is available elsewhere.
  • Hover items (like tooltips) should be initiated with the Tab key in addition to the mouse's hover.
  • Make the focus indicator more visible. The the outline around the highlighted element is essential for navigation for many, but the default outline is often only barely noticeable. You can modify this to be more visible through the use of the focus command to define a style which draws attention on what's currently being focused. It is possible to do the same using the hover function to increase the effect of cover. One good way to modify focus in action is derived from accessibility guidelines from the University of Washington:
a 
 color: black;
 background-color: white;
 text-decoration: underline
 
 a:focus, a:hover 
 color: white;
 background-color: black;
 text-decoration: none
 

This code snippet makes it possible for links to be displayed as black text on white backgrounds, but change into white text on a background when placed under keyboard focus (when the user clicks on the link). This same effect is seen upon hovering as well.

11. Implement Naming Conventions

It will also help you save a significant amount of time on debugging later because it is less likely that you'll refer to the wrong element when writing your code. According to FreeCodeCamp the best practice is to adhere to the standard formatting of CSS names, i.e. font-weight vs fontWeight.

Utilize BEM Naming Convention BEM Naming Convention

One way to ensure names consistent is by using to use the BEM Naming Convention. The entire purpose of BEM is breaking down the user interface into components that you are able to reuse over and.

BEM is a short form for Block, Element, and Modifier. Let's look at what that actually means.

  • Block:A block could be any chunk of design on your website like the header, menu, footer, or column. Your blocks should have names that are similar to .main-nav as well as .footer.
  • Element. Elements are the pieces and bits which make up every single block. Consider things such as the colors of buttons, fonts and lists or even links. If you are using the BEM name convention, elements are identified by placing two underscores before the element's name. So if we were wanting to discuss the font you use in the header on your site, it would look like this in CSS using the BEM namestamp: .header__font
  • Modifier. The last piece to this BEM puzzle will be the modifier. Modifiers determine the styling of the element within the block. This includes things such as font names, weights, and sizes; color values and alignments. If we continue to follow the above example If you want to set the font color inside the header, create it in the following manner with the element and modifier separate by two hyphens .header__font-red

The following naming conventions or whatever your team decides on - could result in a much enjoyable editing and debugging further down the line.

12. Beware of the Important Tag

Another good idea to integrate in the CSS practice is to avoid overusing the important tag for as long as possible.

What it boils back to is particularity. If a selector is very particular, the browser will decide that it is more significant than when using selectors that are less specific. The !important tag can be used to identify the properties that are more crucial than others.

It can be a challenge as often you'll end up having to utilize multiple tags, each of which will take precedence over the previous one in specific scenarios. When you're doing it too often, it could cause your website to break or your styles to load incorrectly. Typically, this code is employed as a temporary option, but in the end it's permanent and then can cause issues later when it's time to investigate specifically.

One of the few instances using the !important tag is considered to be acceptable in general is the ability of the end-user to override the styles to use screen readers as well as other aids to accessibility. It's also useful when working with classes for utility.

13. Utilize Flexbox

There is also the possibility of getting more value from Flexbox as you try to incorporate the best practices in dealing with CSS to your workflow. Flexbox can be used in a variety of ways to design a layout for your website and align components on the page, rather than using the traditional float alternative.

According to CSS-Tricks, Flexbox is a flexible box component that offers an alternative method of structuring your CSS by paying attention to the way your layouts are aligned and dispersed within a container. One of the best features is that the dimensions of the container doesn't even have to be known, and more importantly, the properties inside can "flex" according to the change in dimensions of the container. This is a fantastic method to make room for mobile devices.

Another key difference is that the Flexbox is "direction-agnostic," meaning its layouts aren't structured vertically or horizontally. This is a good alternative for developing complex web pages and apps that need to be able to accommodate many screens with different orientations. The standard CSS layouts are block-based , and flexbox layouts rely on "flex-flow". The CSS-Tricks website also provides concise drawing that illustrates this concept well:

Screenshot of an illustration of how flexbox layouts work from CSS-Tricks.
Flexbox layouts and how they work is based on CSS-Tricks

The elements within the flexbox are laid out along the principal axis and also the the cross-axis and each component as well as its property is created to move and flow in accordance with the flex container's size.

14. WordPress Tip: Never directly alter the theme files

Alternately, you may make use of the Optional CSS option in the Theme Customizer to make any adjustments you'd like to make. It is important to keep in mind this does introduce the CSS inline and will place it directly in the head.

If you are only looking to make a change one or two times, this could be an option but anything you put in the Additional CSS box will remain in place regardless of whether you do an update to your theme, website update, or changing themes.

If more extensive CSS modifications are necessary, you're better off adding them to a custom CSS stylesheet or by using an existing child theme in which you edit the style.css file for the theme's child directly. This method is also update-proof.

Summary

In the process of creating effective and reliable CSS could seem like an overwhelming taskfor a true newbie however, taking the time to educate yourself on most effective practices could make a huge difference in time, effort and headache later on.

Save time, costs and maximize site performance with:

  • 24/7 help and support 24/7 support from WordPress experts in hosting, available 24/7.
  • Cloudflare Enterprise integration.
  • Global audience reach with 34 data centers worldwide.
  • Optimization through the integrated Application for Performance Monitoring.