7 Important Tips for Writing Better CSS (2024)

/ #CSS
7 Important Tips for Writing BetterCSS (1)

By Cem Eygi

One of the biggest issues in programming is dealing with maintenance. In a real-world scenario, we don't always start developing projects from scratch. Mostly, we are assigned (or take) a project that has already been written maybe a couple of years before or even longer.

To work efficiently on that project, first we need to understand the source code. This is the point when we immediately realize the importance of clean code. As developers, we must try to write our code as cleanly as possible.

This is also the case for CSS. There are some points we need to pay attention to while writing CSS. In this post, I would like to share some of the most important ones with you. I believe these 7 tips will help you to improve the quality of your CSS code.

So let's begin...‌ ‌

1. DRY

DRY stands for "Don't Repeat Yourself". This is a general software development principle and can be applied in any programming language, as well as in CSS. As we can understand from its name, DRY aims to avoid or reduce repetition as much as possible.

For example, we can create 3 CSS classes for 3 buttons like this:

.primary-button { background: blue; color: white; border-radius: 5px; padding: 10px 20px; text-align: center; font-size: 16px;}.form-button { background: green; color: white; border-radius: 5px; padding: 10px 20px; text-align: center; font-size: 16px;}.cancel-button { background: red; color: white; border-radius: 5px; padding: 10px 20px; text-align: center; font-size: 16px;}

Or we can use the DRY principle by writing the common rules once in an additional class and the different rules each in other classes:

.button { color: white; border-radius: 5px; padding: 10px 20px; text-align: center; font-size: 16px;}.primary-button { background: blue;}.form-button { background: green;}.cancel-button { background: red;}

As we can see, applying the DRY principle avoids repetition, decreases the number of lines, and improves readability and even performance.

2. Naming

Naming CSS selectors is another important point for writing better CSS. The name of a selector should be self-descriptive and readable...

// BAD NAMING.p { // Rules}.myFirstForm { // Rules}

Normally,

is an HTML tag and stands for paragraph. Above, we can't really understand what class p is. Also, you should avoid names like myFirstForm, and I don't advise using camel case.

Instead, use declarative names (separated by a dash for multiple names):

// GOOD NAMING.article-paragraph { // Rules}.contact-form { // Rules}

I think the names make more sense now :)

Naming things in programming is not that easy, but there are various naming conventions that you can use in your project. BEM (block element modifier) is one of them. I've worked with BEM before and I can recommend it.

3. Don't Use Inline-Styles

Well, there are arguments on the web about this: some are telling you never to use inline styles, while others are arguing that it can be useful in some cases.

In my opinion, the best practice is actually not using inline styles. I will focus here on why we shouldn't.

Separation of Concerns

According to the separation of concerns principle, design (CSS), content (HTML) and logic (JavaScript) should be separated for reasons like better readability and maintenance.

Including CSS rules inside HTML tags breaks this rule:

<div style="font-size: 16px; color: red;">Some Text</div>

We should rather keep our styling rules in external CSS files.

Difficulties in Search

Another problem with using inline-styles is that we can't search for them. So when we need to make a change on styling, we normally look for CSS selectors of the HTML element.

For example, let's change the font-size of text on our webpage. To do that, first we find that specific part on the browser where the change is needed by looking at the HTML structure:

<div class="text-bold">Some Text</div>

Then we need to find the selector, which is the text-bold class here. Finally, we go to that class and make the changes:

.text-bold { font-size: 16px; // change the font-size to 14px font-weight: bold;}

But if the rules are written inline-style instead of using classes:

<div style="font-size: 16px; font-weight: bold">Some Text</div>

Even if we find the HTML tag, we can't know whether there are other font-size rules inside the HTML or not. Since there is no selector used, we have to go through all the HTML pages one by one, try to find the other font-size rules and change them too.

Wouldn't it be easier with a CSS selector? But there's something even worse…

Specificity / Overwrite Issues

Inline-Styles have the highest specificity among CSS selectors (when we don't count !important tags).

Considering we are using both a class and an inline-style for an element:

.text-bold { font-size: 16px; font-weight: bold;}
<div class="text-bold" style="font-size: 14px">Some Text</div>

Here, the font-size of the text will be 14px, because inline-styles have higher specificity than CSS classes. When you make a change in the class:

.text-bold { font-size: 20px; font-weight: bold;}

The font-size will still be 14px. So your change in the CSS class won't work, which will cause you to end up saying:

"Hey, why is my CSS code not working? I hate CSS!"

and lead you to use an !important tag which does the magic:

.text-bold { font-size: 20px !important; font-weight: bold;}

Which is a big no-no and leads us to the next point…

4. Avoid the !important tag

OK, so your CSS wasn't working as was supposed to, and you made it work by applying the important tag:

!important

What happens next? The !important tag has the highest specificity of all CSS selectors.

You're basically saying to the browser to apply that specific rule with the !important tag always and under any circ*mstances. This is not good because CSS rules can differ from one selector to another, from parent selector to child.

The only way to override an important tag is to use another important tag. And this leads to using more and more important tags. Trust me, in the near future your project code will be full of !important tags, which makes your CSS code much harder to maintain. So try not to use it.

5. Use a Preprocessor

Working with a CSS Preprocessor like Sass or LESS is very useful in bigger projects. A preprocessor brings additional features to our CSS code that we normally can't do.

For example, we can define variables, functions and mixins, we can import & export our CSS files in other CSS files and we can write nested CSS code:

7 Important Tips for Writing BetterCSS (2)Sass Code Example

A preprocessor has its own syntax and later it gets translated into standard CSS (in a separate CSS file) because browsers don't understand the syntax.

I like working with Sass and have used it in various projects. I have covered some of the advantages of using a CSS Preprocessor here.

6. Use Shorthands

Some of the CSS properties like paddings, margins, fonts and borders can be written in a much simpler way by shorthands. Using shorthands helps to reduce the lines of rules.

So without shorthands, a CSS class would look like this:

.article-container { padding-top: 10px; padding-bottom: 20px; padding-left: 15px; padding-right: 15px; margin-top: 10px; margin-bottom: 10px; margin-left: 15px; margin-right: 15px; border-width: 1px; border-style: solid: border-color: black;}

and with shorthands it looks like this:

.article-container { padding: 10px 15px 20px 15px; margin: 10px 15px; border: 1px solid black;}

You can find here more info about how to use shorthands properties and for which CSS properties they can be applied.

Normally, quality code doesn't need comments because it should already be clear and self-descriptive. But still, in some cases, we may need to write additional explanations.

// Your Comments.example-class { // your rules}

So when you feel that some parts of the code are unclear, then don't be afraid to add comments (but on the other hand, make sure not to overdo it :)).

As a Frontend Developer with a couple of years of experience, these are the most important tips that I can suggest for improving your CSS skills. If you have any questions, or you think there are also other tips for writing better CSS, don't hesitate to comment down below.

If you want to learn more about web development, feel free to follow me on Youtube!

Thank you for reading!

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

If you read this far, thank the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTIsem*nT

7 Important Tips for Writing Better CSS (2024)

FAQs

How to write CSS better? ›

7 Important Tips for Writing Better CSS
  1. DRY. DRY stands for "Don't Repeat Yourself". ...
  2. Naming. Naming CSS selectors is another important point for writing better CSS. ...
  3. Don't Use Inline-Styles. ...
  4. Avoid the ! ...
  5. Use a Preprocessor. ...
  6. Use Shorthands. ...
  7. Add Comments When Necessary.
Sep 29, 2019

How do I make my CSS better? ›

If either (or both) of these things are something you aspire to, let's talk about CSS best practices that allow you to do so.
  1. Make Your Code Readable. ...
  2. Format Your Style Sheet Well. ...
  3. Rid Yourself of Redundancy. ...
  4. Important: Avoid ! ...
  5. Consider Using a Framework. ...
  6. Use a Reset/Normalize Your CSS. ...
  7. Built Accessibility Into Your Design.
Nov 16, 2022

How to write CSS neatly? ›

Best practices to write a clean and efficient CSS code
  1. Start with a framework. It is recommended to use a CSS framework with each design, as it will speed up the production. ...
  2. CSS reset. ...
  3. Maintain consistency. ...
  4. Ensure it's readable. ...
  5. Avoid the ! ...
  6. Keep it DRY. ...
  7. The right usage of CSS shorthand. ...
  8. Use multiple stylesheets.

How to get better at CSS styling? ›

Tips to keep your CSS tidy
  1. Does your project have a coding style guide? ...
  2. Keep it consistent. ...
  3. Formatting readable CSS. ...
  4. Comment your CSS. ...
  5. Create logical sections in your stylesheet. ...
  6. Avoid overly-specific selectors. ...
  7. Break large stylesheets into multiple smaller ones.
Aug 7, 2024

How do I write CSS like a pro? ›

It is easier to write the CSS selectors in the same order as the elements of the page. So first you have the general styles, for the whole page then the Header, Navbar, body etc. This way when you need to do a change it is very easy to quickly jump to the correct lines in your CSS file.

Why is CSS so tricky? ›

I think part of it for me is that I do not have an intuitive understanding of the box model and how layouts are calculated. On top of that, since CSS cascades, you have to be able to mentally keep track of all the parent attributes to understand how they affect a specific element on the page.

How to optimize your CSS? ›

And here's the TL;DR for delivering optimized CSS for better web performance:
  1. Minify CSS to reduce file size.
  2. Use shorthand and inheritance to limit the code needed.
  3. Get rid of unused CSS properties in old code.
  4. Compress CSS server-side to use the same CSS with less data.
  5. Preload and server push to deliver it faster.

How to best practice CSS? ›

CSS best practices you should know
  1. Use a CSS Preprocessor. CSS preprocessors like Sass or Less can help you write more organized and modular code. ...
  2. Organize Your Code. ...
  3. Optimize your selector definitions. ...
  4. Understand CSS specificity rules. ...
  5. Avoid using the ! ...
  6. Minimize Nesting. ...
  7. Modularize Your CSS. ...
  8. Responsive Design.
Sep 4, 2023

How do I make CSS most important? ›

The !important rule in CSS is used to add more importance to a property/value than normal. In fact, if you use the !important rule, it will override ALL previous styling rules for that specific property on that element!

How do I practice writing in CSS? ›

It is almost impossible for a CSS aspirant to crack essay paper with weak, irrelevant and outdated knowledge. So, Reading is an essential aspect of improving one's writing skills. Adding to that, the other most significant component of polishing one's writing skills is Doing Writing Practice on daily basis.

How do I make my CSS form look better? ›

Adding a solid border for text fields, select boxes, and buttons will keep them equal in height. Adding a slight border-radius will make them look more polished, and padding will provide some breathing room for the buttons.

What is the hardest thing to do in CSS? ›

  • Positioning , Centering.
  • Siblings.
  • Combinators.
  • em vs rem vs px.
  • CSS rule / writing order.
Sep 28, 2019

What is the best way to practice CSS? ›

If you want to learn HTML and CSS skills and start making money, here are some great practice projects to help you get started.
  1. Build a Portfolio or Simple Personal Website. ...
  2. Make your resume interactive. ...
  3. Create an Email Newsletter. ...
  4. Make a static responsive website. ...
  5. Build a form. ...
  6. Create an animation.

How do I make text look better in CSS? ›

CSS provides four common properties to alter the visual weight/emphasis of text:
  1. font-style : Used to turn italic text on or off. ...
  2. font-weight : Sets how bold the text is. ...
  3. text-transform : Allows you to set your font to be transformed.
Jul 25, 2024

How can I make my CSS more efficient? ›

And here's the TL;DR for delivering optimized CSS for better web performance:
  1. Minify CSS to reduce file size.
  2. Use shorthand and inheritance to limit the code needed.
  3. Get rid of unused CSS properties in old code.
  4. Compress CSS server-side to use the same CSS with less data.
  5. Preload and server push to deliver it faster.

How do I make CSS more readable? ›

Information: Readable CSS

You can add whitespace and comments to your stylesheets to make them more readable. You can also group selectors together, when the same style rules apply to elements selected in different ways.

Top Articles
Preservation Methods Brining, Curing and Smoking — The Culinary Pro
Learn how the BBC is working to strengthen trust and transparency in online news - BBC News Azərbaycanca
Worcester Weather Underground
Tlc Africa Deaths 2021
Access-A-Ride – ACCESS NYC
craigslist: kenosha-racine jobs, apartments, for sale, services, community, and events
Kaydengodly
Botanist Workbench Rs3
Georgia Vehicle Registration Fees Calculator
The Best Classes in WoW War Within - Best Class in 11.0.2 | Dving Guides
Osrs But Damage
OSRS Dryness Calculator - GEGCalculators
Craiglist Galveston
Wisconsin Women's Volleyball Team Leaked Pictures
Pekin Soccer Tournament
How To Cancel Goodnotes Subscription
The Grand Canyon main water line has broken dozens of times. Why is it getting a major fix only now?
Ukc Message Board
TBM 910 | Turboprop Aircraft - DAHER TBM 960, TBM 910
Hewn New Bedford
Melissababy
Allybearloves
Air Traffic Control Coolmathgames
Wkow Weather Radar
Bòlèt Florida Midi 30
University Of Michigan Paging System
104 Presidential Ct Lafayette La 70503
Sorrento Gourmet Pizza Goshen Photos
January 8 Jesus Calling
1773x / >
Umn Biology
Imagetrend Elite Delaware
Poe T4 Aisling
Devotion Showtimes Near The Grand 16 - Pier Park
Alima Becker
In Branch Chase Atm Near Me
Solve 100000div3= | Microsoft Math Solver
Http://N14.Ultipro.com
Helloid Worthington Login
Body Surface Area (BSA) Calculator
WorldAccount | Data Protection
Armageddon Time Showtimes Near Cmx Daytona 12
Divinity: Original Sin II - How to Use the Conjurer Class
Honkai Star Rail Aha Stuffed Toy
3500 Orchard Place
Access to Delta Websites for Retirees
Dlnet Deltanet
Pelican Denville Nj
Rocket Bot Royale Unblocked Games 66
Cbs Scores Mlb
Latest Posts
Article information

Author: Annamae Dooley

Last Updated:

Views: 6539

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Annamae Dooley

Birthday: 2001-07-26

Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

Phone: +9316045904039

Job: Future Coordinator

Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.