Write Better CSS: From Hell to Heaven (Part 1)

Tram Ho

Write Better CSS: From Hell to Heaven (Part 1)

introduce

  • Through my experience, through many projects working with front-end, I met a lot of colleagues who found it quite difficult to write CSS, edit and maintain, with some people writing CSS as chores, 1 one of the reasons for that may be that they have never been taught how to write good CSS in the first place or don’t know what good CSS is, which affects code efficiency and quality, which we do not want, so I want to share with you some experience to write better CSS, because there are quite a lot of things to share, so I will write Part1 first, so in this Part we will learn about what is good CSS Code? (more precisely, what is not good CSS), I will forcus on tips and tricks to avoid creating a mess of CSS ? .
    Note : these are instructions that I have gathered through my experience and it works well for many projects I have done. Lastly, apply the method that suits you.

Request

  • I assume that you are looking for tips to improve your CSS writing skills, so you have a basic knowledge of CSS and know how it works, besides, you will need more:
    • Definition of fulfillment

    You should be familiar with the browser / devices you want to work with, here is an example of what could be a definition of implementation: – Browsers: Chrome> = 63, Firefox> = 57, Edge> = 12 – Devices: Laptops with resolution> = 1366 * 768
    This is a website where you can see which CSS features are supported in browsers:

    • What is a good understanding of priorities

    Here are the basic rules of priority:
    Characteristics to determine which CSS rules are applied by the browser, if two selectors are applied to the same element, the one with the higher properties will be applied.

    • Here are some rules to which the feature will take precedence:
      • Inline styles will take precedence over ID selectors, ID selectors will take precedence over Classes and attributes (:: hover, :: before, :: after). Classes will take precedence over elements.
      • A specific selector is better than any less specific number of selectors, e.g. .list will be more specific than div ul li.
      • Increasing the number of selectors will result in higher priority, e.g. .list .link will be preferred over .list and .link
      • If two selectors have the same property, the last selector read by the browser will be applied
      • Although !important has nothing to do with the properties of the selector, it’s good to know that a !important Usage statement will override any regular declarations, and when there’s a conflict between two keyword !important statements The last will apply

    This is a very good website to calculate the properties of a selector

    • Some knowledge about pretreatment

    Preprocessing helps us write CSS code faster, they also help create code that is easy to understand and customize using variables. Here I use SCSS syntax (my favorite preprocessor but there are others like LESS / stylus ) in the example.

    An example of what you can do with word processors:

    CSS variables can now be implemented using native CSS but preprocessors still dominate readability / usability.

  • You should not do anything

    I will show you what you do NOT want to do and explain why doing so will lead to problems over time.

    • Do not write CSS without comments
      I put this point first because I believe that it is the most influential thing you can act immediately, like in other languages, that CSS needs commenting. Most stylesheets have no comments, and when I advise you to write comments, I’m not talking about this:

    Those are bad comments because they have no purpose and do not convey additional information. A good CSS comment will explain the intent behind a selector / rule, here is an example of some good comments:

    • So, what should you comment?
      • CSS hacks
      • Each line you did not write or you wrote 6 months ago or more, in which you need more than 10 seconds to understand its intended purpose.
      • Magic values: speak below this.
    • Do not use magic values.

      What annoys developers when reading or maintaining CSS is the general feeling of black magic , which means you put a rule here and 1 !important there, with a width value that’s great and it works, You feel very ma giáo , but magic does not exist, busy need to have a more scientific approach to clarifying CSS, writing good comments is one thing, stopping writing value in an unscientific way is 1 other thing.

      Here is an example:

      At the above values ​​there is a problem? Because once again they don’t convey their intentions, so what’s the better thing?

      • Use preprocessor variables to add meaning to ambiguous values
      • Please make the exact calculations, after tedious testing on Chrome dev tools you may find that your initial initial value is not the most accurate
      • Commenting to explain why this value is there
      • Find ways to change that value to make it more reasonable

    For example:

    • Do not use px units everywhere
      If you are not main about CSS, it may not sound right, but in fact you should not use them. But in most cases, pixels have never been the best device to use. Why is that? Because they do not scale the font size or device resolution. This is a good website for you to know more about which applications will be used in which context, a quick reminder:

      • px: No scaling, use for borders and base font size in html
      • em, rem (> IE8): Expand with font size. 1.5em is 150% of the current element’s font size. 0.75rem is 75% of the body of the html element. Use rem for typography and everything vertically like margins and paddings . Use em wisely for font-related elements and use it for media query breakpoints
      • %, vh, vw (IE> 8): Expand with resolution. vh and vw are percentage of frame height and width, these units are perfect for layouts or calculations to calculate available space alignment (min-height: calc (100vh – # {$ appBarHeight}))
    • Do not use !important
      • You should keep the selectors priority as low as possible. If not then you will override the previous declaration. If you tend to overwrite your styles, time will gradually build inline styles and use !important and then a nightmare to create more specific CSS rules.
      • Using !important is a sign that you are working against yourself =)). Instead, you should find out why you have to do this. Maybe refactoring the affected classes will help you or separate the shared CSS into another layer that will allow you to not use !important and keep the selectors priority as low as possible.
      • You should only use it when there is definitely no other way in particular than using an external trial.
    • Do not use IDs as selectors
      • Using an ID instead of a class loses the reuseable nature of the code.
      • Instead of using IDs, try to write code that can be reused in the future, if you need to prioritize the elements, add a Class in the lowest level of the DOM tree, at least use the Class with the name. that you set for ID.
      • Here is an example:

    • Do not use HTML elements as selectors
      • Once again remember: Keep the lowest priority possible. Using HTML tags as a selector will go against this because you will have to add more priority selectors to override them later. It will be very inconvenient when you use it in another context. For example:
      • Should not:

      • Better:

      • However, there are a few cases where you can use them, for example when a user wrote something like a blog post with pure HTML output (thus preventing you from adding custom class).

    • So, what to do after reading here?
      • Try to understand how the CSS declaration really works
        • There are a few declarations you really want to understand, because if you don’t, you will still have a ma giáo feel in the code, for example: vertical-align: middle; margin: 0 auto; all the things!
        • What you should know (small reminder: if you think you are unable to explain to someone clearly, click on the links):
          • The box model (width, height, padding, margin, border, box-sizing, display: block / inline / inline-block).
          • Positioning and positioning contexts (position: static / relative / absolute / fixed, z-index).
          • Typography (font-size, font-weight, line-height, text-transform, text-align, word-break, text-overflow, vertical-align)
          • Selectors (*,>, +, :: before, :: after,: hover,: focus,: active,: first-child,: last-child,: not (),: nth-child ())
        • Bonus a few more:
      • Practice working with Flexbox and Grid
        • If your DONE definition doesn’t include testing on older browsers and you don’t use or don’t know about flexbox or grid models, then you should reconsider, they can solve a lot of dad problems. Department that. You can learn them here:
      • And the most important is DIY
        • Frameworks are like Bootstrap or other frameworks: they are very useful for small and fast projects when you do not have time for style design. But in many medium and large projects, don’t use them
        • Over time, you will need to overwrite them and it will take more time than you do by yourself, it will create a more complex and more specific code.
        • Besides, DIY will make you learn a lot, UI designer is the whole job of creating a UI from beginning to end, it is really a challenge. First, try to recreate the look and feel of the websites you like (you can see the code with the support tools). My personal experience is the moment I throw Bootstrap in the trash for my personal project and start coding my own CSS.

I hope that with these best practices, you will feel more comfortable writing CSS and improving the quality of your code.

Share the news now

Source : Viblo