How To Improve CSS Code For Developer 
Tags: html, css, beginners, webdev
Published: 2021-09-02 09:05:12

Today we're going to learn about common CSS writing practices and conventions to make it easier for maintain better code when writing in large web projects. !

Usually when we write code, making how code work is the most important. But when the code has run, the next problem you need to pay attention to is how to optimize that code as best as possible (often called clean code). Because this will help you easily edit, maintain the code as well as increase the loading capacity of the website better.

#Setting Reset for CSS File
If you notice, each browser will have a way to set its own default style for HTML elements, so the padding, margin, border... of these elements will often display differently in different browsers.

The fact that we use the CSS file reset code will help the elements of the web page be displayed in a uniform way on many different browsers. Below is the Reset CSS code of author Eric Mayer's, which in my opinion is appreciated by many programmers.

{% codepen https://codepen.io/haycuoilennao19/pen/bGRebLp default-tab=css %}

You just need to copy this code and put it in the first place in the CSS file and you can use it! If you want to learn more about author Eric Mayer's and explain how the CSS Reset code works, you can visit [CSS Reset](https://meyerweb.com/eric/tools/css/reset/).

In addition, you can also use the Normalize.css file to reset the CSS for your website!

![Normalize.css](https://res.cloudinary.com/dn4nxz7f0/image/upload/v1604383791/cach_viet_css_tot_hon/Normalizecss_2_xl4byg.png)

[Link Normalize](https://necolas.github.io/normalize.css/)

#Don't Repeat Yourself
This is considered a very important element and is often used in most programming languages including CSS. With the main purpose is to reduce the repetition between the code in the web page. To help you visualize, I will create two examples of setting CSS properties for buttons with the code below:

{% codepen https://codepen.io/haycuoilennao19/pen/RwgRbJX default-tab=css %}

As you can see in the code above, between the two classes .button-send  and .button-receive will have some similar and different properties:
* Same: color, border-radius, padding, font-size and text-align.
* Different: background.

Because there are so many similarities, we should use a class .button to collect all the overlapping properties between the two classes. This will help the code to be easily editable as well as not repeat the information in the CSS code. To make it easier to understand, see the following code after it has been optimized:

{% codepen https://codepen.io/haycuoilennao19/pen/dyRXbqL default-tab=css %}

However, in reality, there will be more complicated factors, so you should carefully check the relationships and correlations between the CSS properties of the element before performing optimization!

#CSS Code Organization
Usually when we need to set the style for certain words in the web page, we will add that attribute to the last position in the CSS file. And of course your code still runs perfectly fine.
However, here will happen a serious problem that some time after you want to find these CSS properties again it is really difficult and time consuming because it is impossible to locate the property.

Therefore, you need to divide the CSS file into many different components, it will be easier to manage such as:
* Reset: Contains only CSS properties that reformat the * style for the browser.
* Header: Contains only CSS properties for header, logo, menu, color...
* Body: Contains only CSS properties for content, images, videos, width...
* Footer: Contains only CSS properties for footer, link...
* Other parts of the site...

#Using Shorthands In CSS
This is a factor that helps you to effectively reduce the number of lines of CSS code as well as reduce the file size significantly. Shorthands are how we combine multiple CSS properties into one line. It is often applied to margin, padding, background, border... properties in CSS. To understand better, see the code below:
Border CSS:
```
.element{
   border-width: 1px;
   border-style: solid:
   border-color: black;
 }
```
Border CSS Shorthand:
```
.element{
    border: 1px solid black;
 }
```

#Set Name For Class Id In Website
Usually we will name the class and id as we want, as long as it matches the class name or id in the HTML element. However, as I see it, the name in CSS needs to converge two factors that are close to human writing (understandable) and cover the function of the class or id in the website.

If you work on large web projects, it is common to name classes according to a common naming rule called BEM (Block-Element-Modifier). It helps everyone when working on a project to understand the CSS naming rules and the task of each component on the website. Thereby creating consistency for the project.
Here is an example named after BEM:
![BEM](https://res.cloudinary.com/dn4nxz7f0/image/upload/v1604408431/cach_viet_css_tot_hon/bem_wmj0ym.png)
If you want to learn more about naming according to BEM rules, you can visit [Link Bem](https://css-tricks.com/bem-101/)

#Don't Use Too Much !important tag
In CSS code, when you set an attribute and it doesn't work, we usually immediately assign that attribute the tag !important. And often the results will change immediately.
However, when you use too much !important tag for CSS properties, it will cause difficult maintenance for the website and also break the flow rule of website elements. Therefore, I recommend that you limit the use of the !important tag as little as possible.

If you want to learn more about the do's and don'ts of using the !important tag, you can visit it [Link smashingmagazine](https://www.smashingmagazine.com/2010/11/the-important-css-declaration-how-and-when-to-use-it/)

#Add Comment To CSS File
It's easy to understand CSS code when you've just written and set up your website. However, after a while you come back and suddenly realize that you really don't remember what these attributes are supposed to do in the website (I often do).
So I searched online and found a pretty good way to comment on the CSS code. This will save you some time later on. At the same time, this will help others when maintaining or editing your project can better understand the code, thereby also shortening the time and effort for coding.

In addition to describing the function of a certain class or id, there are also some cases where you should write a CSS comment:
* Fixes: When working on a project, if you fix a certain property, we should comment why and how to fix it right on that code. (So that others when looking at the code will understand better)
* Reminder: Many times when you haven't fixed the bug (due to overtime), we can comment right on the file to remind us what to do the next day.

#Define Browser Supported CSS Properties
This is an equally important factor when you start designing and developing a web project. Most browsers will support the most basic and common CSS properties.
However, there are also some properties that are not supported by browsers or if you want to use them, they must have a prefix attached. So you will see the CSS property that works in one browser but not in the other.

To solve the above problem, you can check the CSS property for the browser through the Can I use tool. It will give all information about which browser will support and not support that attribute. It also provides additional solutions so you can quickly fix errors for browsers that don't support that attribute.
Here is an image that I tested on the CSS Grid Layout property:
![Can I use](https://res.cloudinary.com/dn4nxz7f0/image/upload/v1604412418/cach_viet_css_tot_hon/caniuse_2_rjxbcr.png)
 [Link Can I use](https://caniuse.com/)

#Using Flexbox and Grid In CSS
In my opinion, we should use flexbox or grid to build website layouts because it has provided a lot of utilities to help you responsive layout on many different device screens as well as reduce Depend on framework (Using the framework will cause slow website load time).
If you want to learn more about flexbox, you can visit  [Link flexbox](https://www.niemvuilaptrinh.com/article/nhung-bai-viet-va-cong-cu-hay-danh-cho-flexbox-2020)
If you want to learn more about grid, you can visit  [Link grid](https://www.niemvuilaptrinh.com/article/nhung-nguon-lap-trinh-giup-ban-hoc-css-grid-hieu-qua-va-de-dang-hon)

#Check Unused CSS Properties
When you develop a website, there are many CSS properties that are not used but are still loaded in the CSS file of the website. This will slow down your page load time.
Therefore, I will introduce you to a tool PurifyCSS to help optimize CSS code and remove unused CSS code in the website:
![purifycss](https://res.cloudinary.com/dn4nxz7f0/image/upload/v1604413776/cach_viet_css_tot_hon/PurifyCSS_sc1ffq.png)
 [Link purifycss](https://purifycss.online/)
<a href="https://www.buymeacoffee.com/nhat" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>