CSS : 9 best practices for full-stack developers
Cascading Style Sheets, widely referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what background images or colors are used, layout designs, variations in display for different devices, and screen sizes as well as a variety of other effects.
The CSS specifications are maintained by the World Wide Web Consortium (W3C). Even though every browser supports CSS, there are many inconsistencies in the supported specification version. Supporting all modern browsers is a daunting task, not to mention when developers need to support old and legacy browsers. All these problems cause a lot of trouble for developers, and it is hard for them to write CSS code that will render consistently across all browsers.
As you start to work on larger stylesheets and big projects you will discover that maintaining a huge CSS file can be challenging. In this article, we will take a brief look at some best practices for writing your CSS to make it easily maintainable, and some of the solutions you will find in use by others to help improve maintainability.
1. Keep Your CSS tidy
It is smart to put your stylesheet come in the simplest way that permits you to realize elements of your code quickly. I like to recommend a top-down format that tackles designs as they seem within the ASCII text file. So, an associate degree example stylesheet could be ordered like this:
- Generic Element (body, a, p, h1, etc.)
- .header
- .nav
- .wrapper
It is important to always store details of the CSS code you are using. One of the best practices that you can implement for CSS code is by putting a comment for each group of CSS’s code. It is one of the best ways you can locate the CSS group that you are trying to find for the errors. Use CSS comment structure like below:
/*-----HEADER----- */
add styles here…
/*-----NAVIGATION----- */
add styles here…
/*-----MAIN CONTENT----- */
add styles here…
/*-----FOOTER----- */
add styles here…
Adding comments to your CSS will help any future developer work with your CSS file, but will also help you when you come back to the project after a break.
/* This is a CSS comment
It can be broken onto multiple lines. */
Lastly, provide stylesheet information at the top of the CSS file with comments. Put a Title, Author, Tags, Description, URL information, and so on your stylesheet. This will give the user/developer a reference person to contact whenever they need support regarding your creation.
/*
Theme Name: Developer Portfolio 1.1.0
Description: Cogut Portfolio Website
Author: Cetin Ogut
Author URL: https://github.com/cetinogut/
Tags: Personal , Portfolio, Website
*/
2. Grouping Multiple CSS Elements
When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing. The secret to this efficiency-boosting tactic is the comma. As an example, your h1, h2, and h3 components would possibly share identical font and color. Hence you can combine the same:
h1, h2, h3, h4 {
font-family: Arial, Helvetica, sans-serif;
font-size: 2rem;
color: #f8eaea;
}
You can place any valid selector in a group, and all elements in the document that match all the grouped elements will have the same style based on that style property.
Some designers prefer to list the grouped elements on separate lines for legibility in the code. The appearance of the website and the load speed remain the same. For example, you can combine styles separated by commas into one style property in one line of code:
th, td, p.red, div#firstred { color: red; }
or you can list the styles on individual lines for clarity:
th,
td,
p.red,
div#firstred
{
color: red;
}
3. Use CSS Naming Convention
One of the main advantages of CSS is the ability to separate designs from content. You’ll be able to change the entire design of your website by simply modifying the CSS without ever touching the markup language. Therefore don’t create your CSS by using limiting names. Use additional versatile naming conventions and keep consistent. For instance, if you want to put a class name ‘title-red’, it might look meaningless when you happen to change the color of the title. So using ‘title’ instead of ‘title-red’ would be better. It is suggested that you name the elements on the basis of their properties rather than thinking of what purpose they fit into.
It is also important to use appropriate naming conventions for IDs and classes as this will add value and meaning to your work.
There are only two hard things in Computer Science: cache invalidation and naming things. — PHIL KARLTON
Naming things is never easy and the nomenclature of classes and id attributes in CSS is no exception. The problem with bad naming is that it is then difficult to find yourself in its code, so it’s important to find a particular convention to organize yourself well.
The Block, Element, Modifier methodology (commonly referred to as BEM) is a popular naming convention for classes in HTML and CSS. Developed by the team at Yandex, its goal is to help developers better understand the relationship between HTML and CSS in a given project. The BEM approach ensures that everyone who participates in the development of a website works with a single codebase and speaks the same language. Using proper naming will prepare you for the changes in the design of the website.
Here’s an example of what a CSS developer writing in the BEM style might write:
/* Block component */
.btn {}/* Element that depends upon the block */
.btn__price {}/* Modifier that changes the style of the block */
.btn--orange {}
.btn--big {}
In the below-given example, there is a class ‘cylinder’. It has a div tag, which has an ID named ‘new’, and another div tag, which is an id of icons.
.cylinder {width: 960px; margin: 0; padding: 0;}
.cylinder #new {font-family: Arial, sans-serif; font-size: 40px; color: black;}
.cylinder #tagline {font-family: Verdana; font-size: 20px;}
4. Prefer External CSS
The use of external CSS is beneficial. You can pull all the CSS in an external file and include these files in your HTML.
Benefits of External CSS:
- All the CSS are stored within single Stylesheet.
- All the style changes are done in a single CSS for each page (Easier to maintain the website).
- Single CSS will be cached and page load faster.
- Due to the use of external CSS, we can differentiate the CSS like web page layout CSS and Print-friendly CSS.
Use different version of external stylesheet in your HTML as follows:
<head>
<link rel="stylesheet" type="text/css" href="theme.css" media="screen">
<link rel="stylesheet" type="text/css" href="print.css" media="print">
</head>
Two different style sheets for two different media types (screen and print):
“screen” type is the default value and it is optional to code, this type is used for computer screens, tablets, smartphones. The “print” type is used for Print preview mode/printed pages
5. Avoid internal or inline styling
Internal or embedded CSS requires you to add <style> tag in the <head> section of your HTML document. This CSS style is an effective method of styling a single page. However, using this style for multiple pages is time-consuming as you need to put CSS rules on every page of your website.
<head>
<style>
body {
background-color: blue;
}
h1 {
color: red;
padding: 60px;
}
</style>
</head>
<body>
<h1>Clarusway Tutorials</h1>
<p>This is our paragraph.</p>
</body>
Moreover, adding the code to the HTML document can increase the page’s size and loading time.
Inline styles look and operate much like CSS, with a few differences. Inline styles directly affect the tag they are written in, without the use of selectors. Using inline styling shows the HTML code messy. Updating each HTML event style through global CSS is hard. So you always need to avoid inline style. Below is the example related to this style:
<p style="color:blue;font-size:46px;">
I'm a big, blue, <strong>strong</strong> paragraph
</p>
The p
tag with the inline style attribute is the focus here. Full-stack developers do not often use inline styles when creating web pages, for many reasons. The reasons include “semantic markup”, maintainability, reusability, and scalability.
- Semantic Markup
HTML is meant for conveying structured information. CSS is built to style that structured information. When inline styles are used, this clear separation between structured information and styling is blurred. By separating the CSS from the HTML, the markup can be semantic, which means that it can convey as much meaning as possible without being muddled by visual effects.
- Maintainability, Reusability, and Scalability
Because inline styles only affect the tag they are written in, it can be hard to make changes. If you have written the same style 20 times in 20 different <div>
tags, you must edit each of those places whenever you want to make a trivial change. This can be exhausting! By using a single CSS rule in a <style>
tag or a separate CSS file, you would only need to change it in one place.
You gain the most flexibility and power by putting your CSS in a separate CSS file. If you <link>
to that CSS file on more than one HTML page, you can reuse the same stylesheet for multiple pages. If you want a consistent style across your whole website, this is the way to go. When you want to make a change, you will only need to make the change in one file, and it will be seen on each linked page.
Cases for inline styling:
Professional web developers do not use inline styles often, but there are times when they are important to understand or necessary to use. Here are a few places you may see inline styles:
HTML e-mail,
Older websites,
CMS content (e.g. WordPress, Drupal),
Dynamic content (i.e. HTML created or changed by JavaScript)
Emails often include HTML content. When you receive a fancy-looking e-mail, it is either one big image file or it is an HTML e-mail. You can craft HTML e-mails yourself, but they can be tricky. The HTML viewers in email clients are not standardized, and most of them do not allow <style>
tags. For this reason, HTML e-mail often contains lots of inline styles. Some of the styles included may be archaic, to support older e-mail-viewing clients.
Another time you will see inline styles is on dynamic websites that use JavaScript. Often, JavaScript scripts will add inline styles to HTML. For example, a common way to hide a dialog box is to add the inline-style display: none;
.
!important
The !important
rule in CSS is used to add more importance to a property/value than normal.
<div>
<p>This is some text in a paragraph.</p>
<p class="myclass">This is some text in a paragraph.</p>
<p id="myid">This is some text in a paragraph.</p>
</div>
In fact, if you use the !important
rule, it will override ALL previous styling rules for that specific property on that element!
#myid {background-color: blue;}
.myclass { background-color: gray;}
p { background-color: red !important;}
While !important declarations should rarely be used in code, it’s still necessary to understand what this property is and how to use it. Maybe you’ll need to use the !important rule in your user stylesheets. Maybe you’ll take over a website that contains instances of the rule. Whatever the reason, becoming familiar with the !important property is useful step in learning HTML and CSS.
6. Shrinking CSS File Size using CSS Compressors
If you feel that there is something wrong while the CSS codes get loaded over the browsers and it seems to be lagging behind in speed, then there is high time you tried to compress the size of the CSS files. A lot of elements, including line breaks, white spaces, and even redundant CSS styles might be interfering with your CSS file and delaying your site from loading quicker.
So you can use a tool like CSS Compressor and Minifier to get this going.
You can minify your CSS here: https://csscompressor.net/
7. Implementing the CSS Reset
The major goal of a reset stylesheet is to reduce incompatibilities across various browsers — it provides general styles, which can be easily edited and styled as per your requirements.
One of the greatest challenges when developing the front-end design is browser compatibility. Some of the factors that are greatly affected due to browser incompatibility are style aspects, such as headings, line heights, margins, font size and paddings, and so on. These aspects might be inconsistent as they are viewed across various browsers. This is where the Reset Style Sheet comes into the bigger picture.
Very few developers start coding from scratch so Normalize or a CSS reset is almost required for modern frontend development. You have to include this reset CSS style sheet preceding your style definition under the section ‘head’ within your HTML file in order to prevent these from overriding your style definitions that follow. There is an ongoing discussion whether a heavy reset like normalize.css is still required. You can find a well-explained modern CSS reset here.
8. The magic setup
This trick helps you prevent most of the bad layout problems you can encounter in HTML.
Horizontal sliders, absolute-positioned items doing what they want, margins, and padding randomly everywhere: we don’t want them.
* {
padding: 0;
margin: 0;
max-width: 100%;
overflow-x: hidden;
position: relative;
display: block;
box-sizing: border-box;
}
Especially box-sizing: border-box; is a favorite among many web developers, because it solves the problem of padding and layout issues. Basically, when you set a box to a specific width, and add padding to it, the padding adds to the size of the box. However, with box-sizing:border-box;, this is negated, and boxes stay the size they are meant to be.
Then, if you need to change something, you edit it on a specific item.
9. Targeting Elements
Selectors have an inherent efficiency, the order of more to less efficient CSS selectors goes thus:
- ID, e.g.
#header
- Class, e.g.
.promo
- Tag, e.g.
div
- General and Adjacent sibling, e.g.
h2 ~ p
,h2 + p
- Child, e.g.
li > ul
- Descendant, e.g.
ul a
- Universal, i.e.
*
- Attribute, e.g.
[type="text"]
- Pseudo-classes/-elements, e.g.
a:hover
Right to Left
One of the important things to understand about how browsers read your CSS selectors, is that they read them from right to left. That means that in;
selector ul > li a[title=”home”]
the first thing interpreted is a[title=”home”]. This first part is also referred to as the “key selector” in that ultimately, it is the element being selected.
ID’s are the most efficient, Universal is the least
There are four kinds of key selectors: ID, class, tag, and universal. It is that same order in how efficient they are.
#main-navigation { } /* ID (Fastest) */
body.home #page-wrap { } /* ID */
.main-navigation { } /* Class */
ul li a.current { } /* Class *
ul { } /* Tag */
ul li a { } /* Tag */
* { } /* Universal (Slowest) */
#content [title='home'] /* Universal */
When we combine this right-to-left idea and the key selector idea, we can see that this selector isn’t very efficient:
#main-nav > li { } /* Slower than it might seem */
Even though that feels weirdly counter-intuitive… Since ID’s are so efficient we would think the browser could just find that ID quickly and then find the li children quickly. But in reality, the relatively slow li tag selector is run first.
Don’t tag-qualify
Never do this:
ul#main-navigation { }
ID’s are unique, so they don’t need a tag name to go along with it. Doing so makes the selector less efficient. Don’t do it with class names either, if you can avoid it. Classes aren’t unique, so theoretically you could have a class name do something that could be useful on multiple different elements. And if you wanted to have that styling be different depending on the element, you might need to tag-qualify (e.g. li.first), but that’s pretty rare, so in general, don’t.
Descendant selectors are the worst
In other words, a selector like this is an efficiency disaster:
html body ul li a { }
The things we’ve discussed tend to really come into their own (and their absence painfully aware) on larger builds, but they will definitely, definitely help you on builds of all sizes; small or large.
So, by using more classes and fewer descendants, keeping selectors short and portable, keeping selectors element-agnostic, and generally considering maintenance and chance-of-change when writing our CSS, we can really easily improve the quality of our code infinitely
Conclusion
It is well-known fact that best practices may change radically over time. It might depend on your personal or team’s choices. Nevertheless, documenting CSS begins with clear rules and a well-structured code base. When done as part of your workflow, it can also serve as a guide to structure your code and keep it organized as it grows. This has the additional benefit of making it clear where things are and where new code should be added, easing the onboarding of new members while fast-tracking development.
LinkedIn : cetinogut
GitHub: cetinogut