DEV Community

Cover image for 15 CSS3 Best practices of  for beginners to pro.
menomanabdulla
menomanabdulla

Posted on

15 CSS3 Best practices of for beginners to pro.

Whether you are a beginner or an expert in Frontend Development it is important to follow some best practices in order to keep your cascading style-sheet (CSS) optimized and organized.

CSS guy is an artist, as an artist you should have some unique working strategy that’s make your action while working more enjoyable and fun. Here is some tips I share, you could follow and write your style as pro. Wow! let’s get started:

01. Don't put everything in to one CSS file

Case-01: One large CSS file leads to fewer HTTP requests,
which can improve performance.

Case-02: Several smaller file leads to easier organization
which will make development and maintenance cheaper and easier.

Now what should our strategy for both scenarios? That’s a million
dollars question. Okay let me clear your confusion; we can follow
the win-win rules.

“We could use multiple style sheets to keep things better
organized, and then compress them into one file before putting
them on the site, to improve performance.”

02. Follow top-down approach for organize your stylesheet

You can follow your HTML elements hierarchy in your stylesheet. I called it top-down approach, that will help you to write more structured and organized code. You will find top-down approach very handy to find your expected code block form the entire stylesheet.

Follow top-down approach for organize your stylesheet

03. Make UI components

Tried to make some prebuild UI component that you may use in future just simply plug a class name and have some properties.

04. Comment your CSS

For better readability and organized coding, code commenting play insane role. Code commenting helps code refactor in future and helps other developer to understand the project codebase. Code commenting is always good practice. Those developer who write code with proper commenting, have huge market value.

Comment your CSS

05. How to write consistent CSS

Consistent CSS is important for team collaboration as well as in large project. At the beginning part of the project you can set some rules for maintain throughout to your entire stylesheet. It will help you to write consistent CSS.

06 CSS namespacing

CSS namespacing helps you to create a structure that governs how CSS properties get written. If you follow the convention, you’ll be able to write CSS without being afraid of side effects.
Here’s a list of namespaces I use:

  1. .l-: layouts
  2. .o-: objects
  3. .c-: components
  4. .js: JavaScript hooks
  5. .is-|.has-: state classes
  6. .t1|.s1: typography sizes
  7. .u-: utility classes

07. Use BEM or Block elements modifier

Have you worked on large websites that spans more than a few pages? If you did, you probably realized the horrors of not conforming to a robust CSS architecture. You probably would also have researched on ways to write maintainable CSS.

BEM convention is the good choice for well-maintained CSS architecture. If you’ve never heard of BEM before, it stands for block, element and modifier. It looks incredibly ugly when you first feast your eyes on it.

Use BEM or Block elements modifier

I hated BEM to a point where I didn’t even give it a chance when I first got to know about it. I can’t remember what made me try BEM, but I realized how powerful it is to work with it.

08. CSS class nesting or complex selectors

Logically there is no problem with CSS class selector nesting but future will make sense. When you want to modify existing rules this will be a bit complex.There another main reason is when you use complex selectors browser takes more time fir match selectors.

Let me clear how browser trying to interpret selector and decide which element it matches. Lets related with an example.

CSS class nesting or complex selectors

Browser start with the a tag, it will trying to match all the a tags then trying to match next selector then so on.

CSS class nesting or complex selectors

It's not good practice to using tags as CSS selectors because it will try to match for every tag. Try to use more specific selector and reduce complexity.

09. Use CSS preprocessor like SCSS, SASS and LESS

For keeping your CSS DRY(Don’t repeat yourself), use CSS preprocessor like SCSS,SASS or LESS. The biggest benefit to using these preprocessor is that you can define your re-usable code at the top and reuse it by @ include and @ extend throughout all of your CSS.

CSS preprocessor will make your life easier to write modular based CSS, it’s helps to write more organized and more consistent cascading stylesheet. BEM naming convention with CSS namespacing and CSS preprocessor is perfect combo for robust CSS architecture.

10. Reduce redundancy

Reduce redundancy a bit tough, you will not find both case are exact same. In my suggestion if find 70%-80% style match then you could use different class to outsource rest of 30%-20% style. I hope it will make sense.

11. Vertically align any elements using only CSS

For vertically align any elements modern CSS introduce CSS flex and grid system. Those are awesome tolls for dynamically centered any elements.

By Flex:
Vertically align any elements using only CSS

By Grid:
Vertically align any elements using only CSS

12. Try to use shorthand CSS properties

There is lots of way, you can ménage your style but try to stick with best approach. Always try to use CSS shorthand, it will reduce your code as well as give your stylesheet a nice and good looking shape.

Bad Practice:
Try to use shorthand CSS properties

Good Practice:
Try to use shorthand CSS properties

13. Use rem’s or em’s

Using rem’s or em’s is more dynamic way instead of using pixels. Try to use rem’s or em’s rather than pixels.

14. Avoid !important

For avoid code collusion and if you don’t want to break normal flow of browser behavior with your CSS don’t ever use !important. It’s really hard to find-out conflict within !important and refactor the whole codebase in large scale application.

15. Use mobile first development approach

A mobile-first approach to styling means that styles are applied first to mobile devices.
Concern with:
1.Min-Width Media Queries
2.Progressive Enhancement (CSS & javaScript)
3.Content (Not Device Width) Determines Breakpoints

Last Words

I hope you like my CSS3 coding guidelines and front end web development best practices. You can check my 15 Best practices of HTML5 for beginners for give your markup good shape. If you appreciate it or find any errors let me know in comments. Thanks for this journey & Happy Coding.

Top comments (36)

Collapse
 
mariog8 profile image
Mario Golik • Edited

The article is great, well done👌😎👍 I would add a tiny few more useful functions and tips from myself ...I will not describe them here, I will tell the names and I count on the human curiosity...😁

1) use CSS Custom Properties (Variables)
2) use when flex-box single columns/rows , Use Grid when multiple columns/rows.
3) min, max, clamp CSS functions
4) Calc CSS function
5) CSS counters
6) aspect-ratio(video)

And the last and i think most important (for me) Use dev-tools (firefox) when you styling in CSS .We can edit properties directly on fly and testing those.

I hope it will be useful ! See you ! Best Regards ...and Keep on Coding!😉🖐💻

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Use Grid when multiple columns/rows.

Not always; some layouts look like they should be done using display: grid, when in reality they are just a bunch of boxes that wrap over several lines. In these cases, display: flex is still the better option.

Grid becomes useful when you want finer control over the alignment of your elements, specially when you don't want to just fill the grid cells one after another.

Collapse
 
mariog8 profile image
Mario Golik

Awesome suggestion! Context is the King 😉 Could you send or show(link) us some examples this "some layouts" ? Just to reference and knowledge obviously...💻 💡

Thread Thread
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Can't think of any specific example right now, but think product cards for example, where you have 3 of them on each line and they look somewhat like a grid; but really, they can just be in a flex container with flex-flow: row wrap. Same goes for any other listing of items, like users on a social media site, etc.

Thread Thread
 
mariog8 profile image
Mario Golik

Take your time.... I am very patient and hungry for example, By the way learning from example is, in my opinion, one of the best teaching methods 😉
Have You Great Day and do not haste 😎

Thread Thread
 
menomanabdulla profile image
menomanabdulla • Edited

dev-to-uploads.s3.amazonaws.com/up...
Like such layout, you should use grid. It's easily manageable with grid, flex will be most difficult for this one.

Most recently i will bring a series of article based on CSS Grid, stay stick and keep learning. I love your dedication.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

@mariog8 here you have a full ui framework example using flex codepen.io/joelbonetr/pen/PoqzMWL

The refactor using mixins and that was uploaded to a private repo, but this example can show you how easy and handy Flex works, including cards, forms, content blocks and so on with two different approaches as test case/playground.

Thread Thread
 
mariog8 profile image
Mario Golik

thx for great example 😉👍 It is never late to learn.

Collapse
 
menomanabdulla profile image
menomanabdulla

@darkwiiplayer cool, I am totally agreed with you. There is lots of complex layout we can still manage with flex. We can also use grid to solve the same problem, In such case I would love to use flex. Usually I use grid for more complex layout, such multiple rows, cols and also multiple alignment issues. Love your effort man. Thanks a lot.

Thread Thread
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Sometimes it's even easier to use flex, because that way you can just define a desired width for your items and let them wrap wherever they want. With grid, one would have to use media-queries to define cut-off widths for 2, 3, 4, etc. columns. I'd much rather let the browser figure those things out instead of adding special cases for different resolutions 😁

Thread Thread
 
menomanabdulla profile image
menomanabdulla

Exactly, it is.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇
use when flex-box single columns/rows , Use Grid when multiple columns/rows.

This is opinionated, you can fine-tune a flex grid system easily if you understand how it works, it gives you more flexibility than grid can bring.

3) min, max, clamp CSS functions 4) Calc CSS function 5) CSS counters

Those are not good practices, are simply things that you can use whenever are needed.

Collapse
 
mariog8 profile image
Mario Golik

For me it's practice for You simple things ...everyone thinks differently,I respects your subjective opinion .

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

A best practice is a technique or methodology that, through experience and research, has proven to reliably lead to a desired result. In software development we use best practices as well-defined methods that contributes to a successful steps in product/project development. Thus are general statements that -desirably- are followed by each individual to achieve a solid homogeneous joint result for a given tech stack.

Reducing your functions to a single responsibility is a good practice that exerts from the clean code group. Using a given language predefined method or function cannot be a good practice because you simply will use it when needed, so if you state that using CSS min, max and clamp are good practices, you'll need -scientifically- to state all language reference as good practices and even that, they are conditioned to a conditional context.

If you need something to be 100% it's parent width, is it a good practice to use min, max or clamp to achieve this? of course not. You simply do width: 100%.

The same way you will not find statements like "in JS a good practice is to use split method" because it's only good whenever is needed and not "always" or "in any case", instead we say "Don't Repeat Yourself" or DRY principle, which enforces you to use existing code methods or functions instead re-coding them, which can be applied to any case, thus if split method exists you'll use it instead coding a custom split -as long as it fits-.

There's something I need to remember many times in this platform but again here it is: IT is a science, thus there are methodologies, patterns, best practices, tests... you can try different approaches and apply synthetic tests as benchmarks to analyse which one works better or even do A-B tests to see how user interacts with different UI versions of your software.

In conclusion if you say something is good or that is better but you can't tell why using reliable source or public benchs/tests, you are doing what is called opinionated or anti-scientific pattern.

Thread Thread
 
mariog8 profile image
Mario Golik

I respect your essay but I have a different opinion, relax man .😅

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

You didn't get the point, did you? xD

You have no opinions in science, you can theorise, then make a test suite that covers your theory, try things down, get data as result, merge this result with each test case result and extract conclusions from that. Then your investigation will eventually be peer-reviewed to give or take credit, making it more or less reliable or true/false.

I see in your profile that you are a self taught, this probably means that there were no teacher teaching you about that in computer science research methodology, even that, you can learn about software engineering, research methodology, algebra, logic and so on as there are tones of resources extracted from college subjects online for free, it's just a bit harsh in comparison to learn how to code with a given language but this kind of things are what can make you work on a serious well-driven company with -usually- a better salary as well as being able to work on a larger number of companies or roles in the industry.
You can even become a tech lead if you take effort in this subjects (I recommend you to get an official certificate whenever you can as well, it will definitely help you grow in your career).

Finally please, don't pick this words as an offence to you but as a good advice to follow.

Thread Thread
 
mariog8 profile image
Mario Golik

Thank you very much for your valuable advice. I am glad that you gave me tips, it is important and very precious for me. If you find a moment, take a look at my portfolio page and evaluate if you can (I care about constructive criticism) It would be very nice for me ... Have You a great day. See you next time ...😉

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

You're welcome, I'll pin a tab with your portfolio and will take a look at it after the meetings today :D
Have a great day!

Thread Thread
 
mariog8 profile image
Mario Golik

Thanks a lot, fruitful day and successfully meetings 😉👍

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

thanks, I sent you some private messages (chat icon near notification bell icon at the top) :D

Collapse
 
menomanabdulla profile image
menomanabdulla

Great! you added some important points here, Keep doing good stuff and spread it. I appreciate your effort man.

Collapse
 
bert profile image
Bert

Almost everything in this "article" has been copy-pasted from other sources without any reference:
webtips.dev/10-best-practices-for-...
linkedin.com/learning/introduction...
code.tutsplus.com/tutorials/30-css...

Collapse
 
menomanabdulla profile image
menomanabdulla

Please don't give such blame. "Almost everything in this article, has been copy-pasted" how could you say like this. For take inspiration I have read some post it doesn't mean copy past those content. I just start writing articles here and this is my second post here please investigate carefully. If you have full intention to discourage mine then it's different i guess. We need effort to published such article, hope it make sense. Thanks man.

Collapse
 
bert profile image
Bert

No, this makes no sense at all.

How could you say like this

Because it's true, everyone can compare the linked articles with what you wrote. It's copy-pasted.

I just start writing articles here

No excuse at all, on the contrary! It's the absolute minimum requirement for any public writing to reference sources. This is not some "nice to have, please, excuse me, I'm learning" thing! You disrespect other authors who put the work in.

We need effort to published such article

"Such articles" is what will destroy this website in the long run, because it is becoming a dump for hastily copy-pasted blog spam.

Thread Thread
 
menomanabdulla profile image
menomanabdulla

I wrote about such topics there ton of post, articles are available in web. Because that is not a unique topics some one else discuss already some of points on internet, I tried represent it and organized it with my own perception. I must say again please investigate carefully.

Collapse
 
afif profile image
Temani Afif

intresting, let's investigate. Such thing is not allowed here.

Collapse
 
bello4 profile image
bello oladepo

Wonderful article was having much taught as regard my approach when starting to make design, I usually do desktop view first but I find it easy writing responsiveness for desktop than mobile so mobile first approach is best since 70% of users try mobile access first.

Collapse
 
menomanabdulla profile image
menomanabdulla

Glade to know you find it insightful. Let me know, how you gonna use mobile first approach in your next project. Thanks man, happy codding.

Collapse
 
przemek profile image
Przemyslaw Michalak • Edited

We took care of most of those things in our online IDE. It let's to create UI Widgets along with possibility of using over 50 premade one. The IDE (automatically) splits CSS into smaller files allowing to edit singular parts of the website. At export everything is minified. Try it here:
glue.codes
Or watch on YT:
youtube.com/watch?v=OGR7cjZW44Q

Collapse
 
cteyton profile image
Cédric Teyton

Nice post :)
FYI we've added it into a GitHub project gathering content about best coding practices :)
github.com/promyze/best-coding-pra...

Collapse
 
ayabouchiha profile image
Aya Bouchiha

Nice !

Collapse
 
menomanabdulla profile image
menomanabdulla

Thanks a bunch, You can follow for more exciting content.

Collapse
 
prathameshkdukare profile image
Prathamesh Dukare

It was usefull I get to know about CSS preprocessor that i dont knew before

Collapse
 
menomanabdulla profile image
menomanabdulla

Happy to see you find it handy, stay stick more interesting topics on arrival.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
menomanabdulla profile image
menomanabdulla

Nope I meant vertically, for horizontally you need to use "justify-content: center;"
Thanks