SASS nesting(for readability), is it a bad practice? - css

A more experienced co-worker told me to nest all my SCSS, so it would reflect its look in HTML, claiming it would do wonders for readability.
I am really concerned that this is unnecessary and could potentially slow down the application(angular) dramatically.
in the reformatted document, the selectors are going 5 levels in, while in the original it never passed the 3.
What is ts the best practice to use nesting is SASS? should it be used only when it would its necessary for specificity purposes? or it can be a better way for formatting my document?

I would try not to directly nest them in a way that's identical to the nesting of the HTML as you're quite right, you would have an unnecessary amount of selectors in your CSS.
There is a great book on https://smacss.com/ that teaches you to split your code into modules instead. I would recommend sectioning your HTML to blocks/modules and nesting relevant selectors rather than all selectors.
Rule of thumb: the more selectors you include, the stronger priority it holds when styling.
Note: I would recommend looking into stylus as I think this improves readability over SCSS.

Related

Is it possible to nest SASS selector in the source without outputing them nested? [duplicate]

This question already has an answer here:
Is there a SASS rule for outputting a descendant to the root?
(1 answer)
Closed 6 years ago.
For example, I want to make my code easier to read by doing this:
#article{
...
#article_inner{
...
}
}
However, I want it to compile into this:
#article{
...
}
#article_inner{
...
}
Is this possible using SASS?
Yes, #at-root will do what you want.
However, I question the premise of your question.
First, let's assume you really want to write #article { #article-inner {. For this, SASS will generate the code #article #article-inner {. You want it to generate #article-inner {. But why? Presumably you are concerned about the possibly lower efficiency of parsing, downloading, or applying the former as compared to the latter. Actually, though, any differences in efficiency would be miniscule to non-existent.
Second, I wonder why you think nesting the rules is "easier to read". Actually, to me it's harder to read. Presumably you think following the structure of the HTML is going to make it easier to read. Actually, following the structure of the HTML makes your CSS brittle. In computer science terms, this is called "coupling", generally considered a Bad Thing; in this case, you are coupling your HTML too tightly to your CSS. For instance, if for whatever reason #article-inner moved, or appeared somewhere else, then, even though the ID matched, your rule would stop working.
Experienced SCSS coders make very light use of its nesting capabilities. Instead, they write rules that are orthogonal to the HTML, which can be combined to create a number of styling effects, without being slavisly bound to the hierarchical structure of the HTML. Good SCSS coders I know limit themselves to nesting in the case of things like .class { color: red; &:hover { color: blue; } }, or in other cases to one level at most. In your case, if you have to use #at-root to do what you want, you have now actually made your code less readable in the name of readability.
SCSS is not going to live forever. Some day CSS will handle much of what it now does for us, including variables. Some shops are already moving away from SASS, with its ugly, verbose macros, mixins, hard-to-maintain features like #extend, and excessive nesting, back to raw CSS or forward to more modern preprocessors like suitCSS. We need SASS less and less for vendor-prefixing; other preprocessors support modularized, automated vendor prefixing tools. For all these reasons, therefore, it's not unreasonable when writing SCSS today to consider the potential that your code might need to be ported away from SCSS sometime in the future. That would indicate you should avoid using lots of SCSS-specific features when they're not really necessary, such as the nesting in your case.
If you want readability, add comments, which you should be doing anyway.
#article { ... }
/* The `#article_inner` element is inside `#article`.
#article_inner { ... }
More generally, I would question an ID-based approach to writing CSS. Presumably you intend to specify a bunch of properties on #article-inner, like font size, background, padding, or whatever. I've seen CSS where there are a dozen properties or more. What is the point? You might as well just write the properties in a style attribute directly on the element; at least then, you'd only have one file (the HTML) to manage. Instead, knowledgeable CSS designers create small, utility-like classes that can be applied to many elements. For instance, they might define a PaddedGrayBox class, that handles the padding and background. Then, they write in their HTML
<div id='article-inner' class='PaddedGrayBox FloatRight...'>
Now this is more readable. Someone looking at the HTML can immediately see what kinds of styling are being applied. If you take this approach consistently, you may find that you are able to do away with using IDs altogether, although I know that would be quite a departure for jQuery-oriented programmers who believe that doing $('id') (or getElementById) on every other line is the core of JavaScript programming.

css selector specificity conflicts due to multiple stylesheets

Ok, I've been reading through stackoverflow css selectors. on the thread here what is the differences in this syntax? What does the ^= mean? What is it selecting? all?
[class^='Rating']
and
div.Rating0_5
Also, there's a statement here that reads:
Note: Repeated occurrances of the same simple selector are allowed and do increase specificity.
What does that mean?
I'm asking because I'm having to clean up alot of CSS code on a website. There are over a dozen stylesheets each containing 200+ lines of code, and there are styles that are overriding each other among the stylesheets, maybe even within them if repeated occurences increase specificity. It's painstaking to go line by line through the stylesheets to find out what particular class, div, etc is over-riding another and some of the specificity is seven selectors deep! It's almost impossible for me and very stressful.
Is there a tool to use that will target styles overwriting other styles? Is it easy to use and what does it do exactly? If not, how can I write my CSS with enough specificity without having extremely long selectors to hopefully ensure uniqueness so that they will not be overwritten by another stylesheet of rules?
Thanks, I hope this makes some sense and someone has had this experience.
^= is "starts with" for CSS selector. In your case it will apply to classes with names starting with "rating".
With traditional CSS you do have to make really long selectors to be specific and I think the statement meant you can have duplicate selector and the styling will be combined.
In terms of cleaning up the CSS I don't have a good suggestion for an automated tool but you can take a look at http://sass-lang.com/ (SCSS) for a better syntax layer on top of CSS that does variable and inheritance of selectors. Does clean up CSS a lot.

Can the re-usability concept be applied to css?

I was just checking out this page, and came across the fact that CSS can be OO(Object oriented). So, is it possible to apply the re-usability concept of OOPs to css? If yes then how?
It's not exactly OOP but using Sass, in particular its mixins and variables, will help to reuse your CSS.
http://sass-lang.com/
I don't know about CSS being OO, after all it's not even Turing-complete.
As for Sass, it bring complexity to what should remain, imho, a simple static set of rules.
But you can definitely achieve reuse-ability with CSS. Avoid CSS rules related to an ID, as they're not reusable, avoid big CSS definitions with everything from margins to backgrounds to font syle, create short CSS rules that define simple behaviors, then combine these rules by applying multiple classes to your HTML elements like <span class="big emboss red">. Each of these rules has a simple and obvious meaning and can be reused.
A good thing to write well structured and reusable css is http://lesscss.org/
CSS is not really OO in the sense of OOP, but yes, you can reuse CSS. I've used the OOCSS methodology in situations where I'm working with larger development teams on longer ongoing projects. We try to establish a base CSS framework and then build upon that using the OOCSS.
Pros:
developers, with a bit of documentation, can reuse the CSS without having to constantly come back to a UI designer to create new classes for them
should be easier to maintain long term
typically leaner CSS files (as you avoid doing one-off classes more than typical)
Cons:
you tend to have more classes in your markup class attributes
it's not semantic
everyone managing the CSS has to be on board and understand the concepts related to it (else you end up mixing your OOCSS with a bunch of one-off classes and end up with a bigger mess)

LESS/SASS CSS opposite from minification/optimizations?

I wonder can I say that LESS/SASS CSS "pre-processors(I think they are called?)" is the opposite from optimizations like minification? I wonder if there will be any noticeable performance impact? or do you think easy of development is more important?
I ask this because what LESS CSS generates is something like
body #div1 #div2 p
body #div1 #div2 p a:link, body #div1 #div2 p a:visited
...
and I think it can really bloat up my CSS quite a bit. as you can see, such specificity is not required and it makes reading CSS hard (at least what I see in firebug).
In Sass you can control 'specificity bloat' by understanding how nesting works. You don't have to do any nesting at all if you don't want - it's something you can control.
Using the new #extend directive, you can actually reduce redundancy in your CSS by applying the priciples of OOCSS and can thus improve performance. Here's a good article to get you started with #extend. And a few more OOCSS resources:
http://www.stubbornella.org/content/category/general/geek/css/oocss-css-geek-general/
http://wiki.github.com/stubbornella/oocss/faq
http://oocss.org/
The great advantage of #extend in Sass is that it takes the manual effort involved in applying OOCSS and makes it wonderfully painless and easy.
Finally, as Andrea pointed out, Sass has a variety of options for minifying CSS (see the :compressed style), so overall you've actually got a pretty potent toolkit for not only improving your performance as a developer, but also improving the performance of your CSS. For an example of this in action, see how Chris Eppstein, author of Compass and core contributor of Sass, refactors the Digg stylesheet down from 125 lines of code to 85 lines of code (a 32% reduction).
You'd be surprised, but gzipped CSS files that have repeated blocks of code shouldn't be too much larger than ones with the shorter selectors.
This is thanks to how the compression algorithm handles duplicate strings in a file. Instead of including the same string twice, it replaces the second occurrence with a reference to the first one, and so that string only appears in the compressed file once. Take a look at how repetitive the selectors in your generated CSS file are - this should make them compress fairly well.
Naturally, the key to this is making sure your CSS files are gzipped - leaving them uncompressed will definitely increase the file size.
Depending on the options, SASS can give output in different styles. For production, you will want to set the output style to 'compact'.
There is a firebug addon for sass that should make things easier to read. You don't really need to read the output directly anyway.
Sass, less and xCSS will generate more output but I wouldn't call it bloat.
Hand written CSS, with it's many redundancies and duplications will degrade quickly as developers pile name spaces on top of others during the life cycle of the code. One of the symptoms of poorly maintained, designed or written software is bloat. And because CSS has some design deficiencies from the start, even the best CSS coders are effected by this limitation.
So you got to weigh up the initial footprint of your well formatted sass/less file against a hand written CSS file that has been edited a few times over.
Another benefit on sass is that your HTML becomes leaner. You don't need to append class names throughout your code to make up for the flat, global structure of CSS.

Is there an advantage to using very specific selectors in CSS?

I understand that in jQuery, it's advantageous to be more specific when using selectors so that jQuery doesn't have to traverse the entire DOM to find what you're looking for. For example, $('span.description') is better than just $('.description') if I know that the description class is only ever applied to <span> elements.
Is this the case with CSS, too? Is there any specific advantage for me to use span.description { } instead of .description { }? I'm thinking in terms of speed, optimization, etc. Am I saving the browser any work by telling it exactly where to look?
This is true in CSS -
A good rule is to descend from the nearest ID.
IDs are indexed so locating them is extremely fast. There is no reason to use more than one in your selector.
Google Code- Optimize browser rendering
This answered a lot of questions I had on the subject including this one-
I hope you find it useful.
Read up on css specificity - which is the most important reason to be more or less specific with your css.
http://www.w3.org/TR/CSS2/cascade.html#specificity
As browser performance is pretty much a non-issue (except for in jquery, as you've mentioned), my guideline is to be specific when you are controlling precedence, or when you want to make something a bit more readable in your css. Over specifying can make it tricky to re-use css selectors and make things overly complicated.
Edit
This looks like a bit of a duplicate:
CSS Performance Question
it always depends on your amount of html code and the structure. It is definitely a good idea to use especially ids and appropriate selectors. (ie #nav li instead of li.nav). Since browser first load the html and then apply the css you are helping a lot.
This said, when it comes to pure css (no jquery) the difference in speed is nowadays not easy to distinguish, because the rendering engines are highly optimized - especially when it comes to applying css. So normally it shouldn't matter.
As far as I know, how specific your selectors are make very little difference on the performance.
The two areas where more specific selectors are most useful, is to reduce the risk that it's not applied where you don't want it, and to make one selector take precedence over another.
A more specific rule has precedence over a less specific rule, so:
span.myclass {}
has precedence over:
.myclass {}
(no matter what the order is in which the rules were declared)

Resources