Good practices using CSS

Asked

Viewed 2,341 times

16

What are the best practices in CSS to maintain código limpo, compacto and manutenível?

  • Should a simpler and less rigid form of selectors be used? (Scenario: There’s a div with an image inside)

Sample code:

.caixa img{}
ou
div.caixa > img
  • Selectors should be used to group characteristics (e.g., a selector to make the background color green and white letters) or specific for each common element (button with green background color, white letters, black border and bold)?
  • How it should be organized in the archive .css the selectors (e.g.: O Developer adding new selectors at the end of the file)? Should be grouped by archive .html, by element tag HTML, as would be organized class selectors that are generic (eg a selector to make the background color green and white letters).

  • I usually put id in estutural areas of the HTML (body, menu-left, menu-right), and create a selector this way: Is this bad practice? Relieving HTML to the detriment of CSS? it would be better to create a class that would contain all the elements' appearance (which would leave HTML full of classes)

Sample code:

#corpo, #menu-esquerdo, #menu-direito{}

3 answers

18


I would personally recommend that:

  • Always look for simplicity in code. Avoid selectors where not necessary. If you create a selector id for the tag body, for example, you may forget that this id is therefore addressed to her, being more intuitive select by the tag itself. But in the case of elements div, where there is usually more than 1 element of this type on page, it is interesting to identify them with id.
  • It is preferable to create a selector for each element, except when there are many elements with the same feature, hence it is better to use class.
  • It’s interesting to use CSS heritage to your advantage.
  • I would put the styles in CSS in the same order as the elements appear in HTML code.
  • In the case of your example, div.caixa > img seems to be better because it is more specific. This would prevent CSS from "leaking" to elements where it should not be applied.
  • Grouping selectors is interesting when it has similar functions, but they are not in amount that is interesting or does not make sense the creation of a class and this would only make it difficult to read the code.
  • It is interesting to use the selector *, that selects all page elements to give a general CSS reset and avoid problems due to native browser style sheet.
  • It also seems to me a good practice to create a div within the body and put all the content on it if you use third-party plugins on your page, as these usually print the code inside the tag body and thus you could have greater control and reduce the chance of conflict.
  • 2

    I agree with Carlos and still recommend the use of some CSS preprocessor such as SASS or Stylus

  • I would just like to contribute: I like very much that my classes indicate that certain thing is a. Bootstrap for example uses this concept, e.g.: form-control, input-lg, etc... I think this is an interesting approach.

  • Good answer, I only disagree with Cssreset, see: http://stackoverflow.com/a/8357635/1518921

17

CSS is an acronym for Cascading STyle Sheets. The Cascading (cascading, cascading, you choose...) refers precisely to the ability to create type selectors

.container .wrapper ul.lista > li:first-child span

which can be read as "The span within the first child element straight from a class list .lista within a .wrapper within a .container. This type of specificity is one of the most interesting details in CSS, and can be both extremely powerful and dangerous. The big secret, which may answer your question, is knowing when to use a dial rigid, as you put it (the case of my example), and when to be more flexible and simply create a class .meu_elemento, attribute it to <span> and save a lot of lines. Which brings us to good practices (what I consider at least). But first, it’s worth answering a question:

The code is mine?

Nothing better than this gif to explain my point. Once, I had to maintain a code that was maintained by another developer for about 2 years, and then abandoned. In this type of situation, I have always tried to be very specific (i.e., create selectors that will hit as few elements as possible). That way, it’s harder for me to change something by accident.

Once said that, and assuming that you want at all times create a readable and easy-to-maintain CSS, let’s go to good practice:

  1. CSS Reset

    Regardless of the size of your project, whether it’s a bakery website or the largest e-commerce in the galaxy, use a reset. Resets essentially fix inconsistencies between browsers, such as margins, heights, etc. Some frameworks already come with built-in resets, which brings us to the second point.

  2. Frameworks

    Some people twist their noses when they hear the word framework. I already believe that if someone (or a team of somersaults) devoted time to developing something, whose focus is on scalability, why reinvent the wheel? Foundation and Bootstrap perhaps are some of the most famous. I am particularly using (and approving) the Suzy, which is a somewhat less rigid SASS framework. Ah...

  3. Preprocessors

    Variables in CSS? Loops? Conditional? Nesting? Preprocessors allow you all this plus a lot of other advantages. LESS and SASS are the most famous, I believe. Preprocessors, in addition to making your code MUCH more readable, allow you a greater degree of propagation. If you choose more specific selectors, the nesting of the processors, together with their mixins and extends, make things a lot easier. Since we’re talking about specificity...

  4. Ids or Classes?

    It is known from the cradle that IDs define unique elements on your page, while classes are used for repeating elements. Something you NEVER should have <div id="container"> twice on your page. Although this works, and you have no glaring variations in performance, this is not good practice.

    The ideal is that whenever you feel that something is repeating itself frequently in your CSS, it becomes a class whenever possible. If, for reasons, several elements contain the properties float: left and line-height: 1.5, try to create a class containing the two properties and distribute it, according to your logic, by your mark-up. Let the IDs for specific elements or blocks of elements, which merit special attention.

  5. HTML and CSS inline

    If you’re frequently coming and going to your HTML, making adjustments to make your style settings work, you’re doing it wrong. Look, when you can, to define your HTML in the simplest way possible, grouping elements that repeat themselves and avoiding the maximum CSS inline.

  6. Specificity VS Generalization

    Maybe here is the main point of the question. In a code

    <div class="images">
        <img src="/img/1.jpg" alt="">
        <img src="/img/2.jpg" alt="">
        <img src="/img/3.jpg" alt="">
    </div>
    

    I must use, as selector, .images img, div.images img, div.images > img, or maybe a class for images?

    I, in particular, analyze the hierarchy of my code. If I am too generic, and my project tends to increase, it may be that my selector hit something that I didn’t plan. On the other hand, if I am extremely specific, maybe my code becomes too repetitive, because it would be adding the same priorities to more than one class or element, which causes an extreme bloat.

Basically, it all depends on how you architect your project, and how it grows (remember, you don’t always have control over all of HTML). Generalization may be good, but as it tends to achieve more elements, you can get to the point of having a <div> which is pointed out by 5, 6, 7 different rules. The more rules in an element, the harder it is to maintain and change it. Specificity prevents this kind of thing from happening, but it can make your code repetitive and not scalable at all. I believe frameworks help to get around this problem, but nothing that experience itself doesn’t tell you how to do. The secret is to find the point of balance between the two things, without affecting performance, and without causing you to pull your hair out.

EDIT:

Still in time: I found an article that, although old, is quite interesting, and deals with the specifics of the selectors. It can be read here.

3

One of the Patterns design most currently used in CSS is the so-called WELL.

Well, the acronym for "Block, Element, Modifier" is nothing more than using standardized nomenclatures to help a developer identify the function of a CSS class just by tapping his name. She uses the pattern: .bloco__elemento--modificador.

A good example of practical use would be the code below:

<div class="contador">
    <button class="contador__botao contador__botao--subtrair"> - </button>
    <input class="contador__campo" type="number">
    <button class="contador__botao contador__botao--somar"> + </button>
</div>

Where the above example classes would represent:

  • .contador: general block-parent class of what will be stylized;
  • .contador__input: class referring to all inputs belonging to the parent block.
  • .contador__botão: class referring to all buttons belonging to this parent block;
  • .contador__botao--subtrair/somar: button modifier (remains a button, but has a subtype, in this case, "add" or "subtract".

Where by striking the eye, any connoisseur to the pattern would be able to identify exactly the functions of each class without even seeing its contents.

Among the advantages of using BEM as a standard are:

  • Standardization of nomenclature;
  • Easy identification of class functions before you even see the code;
  • Better maintenance and scalability in large projects (because of standardization);
  • Preventing conflict between properties and CSS classes.

Among the disadvantages, we have the main:

  • Aesthetically "ugly" nomenclature (classes with big names);
  • "Cast" of classes (instead of a class .btn for all Uttons, we would have .escopoX__btn, .escopoY__btn, etc..

Well, as well as other patterns in ascendancy in the market has its strengths and weaknesses, and just like any standard in the IT world, it should be evaluated and used according to its utility in the design.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.