What are some problems/drawbacks with nested CSS? - css

I usually prefer Sass over CSS and one big reason is it allows me to write nested rules, which often reduces the amount of code I write.
I wonder, however, if there is any drawbacks of the idea. What could become problematic when writing nested CSS code?

You should only be as specific as you need to be with CSS - it's very easy to get carried away and end up with selectors like div#body #content #sidebar ul.results li a, which is a) horrible to read, b) slower for the browser to interpret, and c) nearly impossible to override if you need to.

I think debugging will be little difficult while using SASS or LESS

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.

Is CSS faster when you are specific?

Is div.container faster than .container ?
You know like in jquery if you be more specific with your selectors it is faster since it iterates through less.. Is this the case with css ?
Is there a way to measure performance in css ?
Performance wise, does things like this even matter or does it all depend on text weight basically ?
I'd be happy if someone knows the answer to it, I've actually found a similar question with no certain answer.
Can CSS be more efficient if it is better specified?
In real world the speed difference would be negligible.
To be technical .container would be faster as it has fewer selectors to process.
Selectors have an inherent efficiency. The order of more to less efficient CSS selectors goes thus:
ID, e.g. #header
Class, e.g. .promo
Type, e.g. div
Adjacent sibling, e.g. h2 + p
Child, e.g. li > ul
Descendant, *e.g. ul a*
Universal, i.e. *
Attribute, e.g. [type="text"]
Pseudo-classes/-elements, e.g. a:hover
In regards to your second question:
Is there a way to measure performance in CSS ?
Steve Souders put out an online test to measure performance of CSS that can still be accessed here.
There are better ways to measure performance nowadays, but this is a quick and easy resource you can play with.
Performance wise, does things like this even matter or does it all depend on text weight basically ?
The short answer is "not really".
The long answer is, "it depends". If you are working on a simple site there is really no point to make a fuss about CSS performance other than general knowledge you may gain from best practices.
If you are creating a site with tens of thousands of DOM elements then yes, it will matter.
delta between the best case and the worst case was 50ms. In other words, consider selector performance but don’t waste too much time on it.
See: https://smacss.com/book/selectors
So I do not think it makes much sense to extend CSS rules ONLY to get a higher performance. Just consider the higher amount of network traffic, maybe worse maintainability, ...
However in the link you can read, which rules to consider without having to increase the CSS size.
If .container and div.container match exactly the same elements on your page, the first one might be even faster: If the browser evaluates .container at first, actually it would have been finished, but with div.container it has ADDITIONALLY to check, whether the element is a div.
disclaimer: I do not know how browsers really implement these things. My conclusions are based on the linked article.
Generally, the fewer the rules the better, so .container would be faster than div.container. Apart from caching, the .container gets read first, then other elements have to have the div added on as a second-level filter... unnecessary in many circumstances.
This is pretty common across engine, though there are some minor deltas.
See this article: Writing efficient CSS, which although it is from MDN (and is therefore Mozilla-geared) holds true for most of what I know about the engines in general.

Nested selectors performance impact and LESS

I have been reading for the past 1.5 hours about this and still couldn't find a concise and decisive answer.
As far as I understood browsers parse CSS selectors from right to left.
That means a long CSS selector such as this:
.card .container .businesscard .pinfo li.pinfo-box span:first-child
is one of the least efficient lines of code to ever appear here in SO.
First of all, am I right on this one?
Secondly, I am designing a rich UI using LESS, which ultimately produces this kind of mammoth selectors out of the nested designs I am coding.
What can be done to avoid this kind of selectors? Rely on classes and IDs alone? But then again what is the purpose of using LESS if you can't write nested CSS?
Your input is appreciated.
That is correct. Browsers evaluate selectors from right to left. It will try to find a span inside a li.pinfo-box and so on.
One rule of thumb to folllow when writing LESS is: do not nest more than 3-4 levels.
This will prevent your selectors from growing to big, while you will still be able to benefit from the nesting feature in LESS.
A good example of "useless" nesting is when styling lists. Sometimes I write the selectors like this:
#wrapper .blog-post ul, #wrapper .blog-post ul li
Is it really necessary to specify that the li must be inside a ul? It will probably be enough writing:
#wrapper .blog-post li
All of this is good to know. BUT: This is not the first thing to dive into when trying to optimize your sites performance. Spend some time lower the number of request or something else instead.
Selector parsing and matching is unlikely to be a big factor unless you have pretty unusual content. I would suggest using whatever is maintainable and gets the job done, up until the point where testing shows a performance issue. Then I'd get out a profiler (on OSX I'd use Instruments, but there should be a decent one available for most platforms) and attach it to the browser; if selector matching shows up high on the profile, then look into replacing slow selectors with faster ones (id selectors are definitely a good bet).

CSS selector performance

I know the performance difference is miniscule, but which is a faster CSS selector?
div.class{ }
or
.class{ }
CSS Selectors are parsed right to left, and then displayed, and the full rule is always parsed. So that would lead me to believe that .class is slightly quicker than div.class. That said, there's also the time taken to render the page, so it may depend on how many elements have that class and how complex the rule is.
Now with all of that said, check out the first answer here: https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil
The performance difference is so minuscule (if detectable at all) that it's not worth even thinking about.
Use div.class if you need some styles to only apply to div elements with that class, use .class otherwise. Base your decision on what your styling needs are, not some infinitesimal performance benefit.
Note: There are some selectors that really are (relatively) slow and might be worth changing, things like .class > *. But, even for selectors with really bad performance, and even if you're at a reasonable stage in your project to start thinking about optimizing things, there are exactly a million things you should worry about first before you get to CSS selector optimization.
I think it may depend on browser, you can check selectors here:
http://jsperf.com/jquery-performance-bn/3
In my browser (Opera 11.62) div.class was a lot faster.
.class {} selector is faster than div.class {} because in the first case browser only checks that the element has specified class, whereas in the second case it additionally has to check the element is actually a div.
I don't even remember asking this question at this point, but here's the jist:
The performance difference is minute, EXCEPT when using a JS library like jQuery. To evaluate $('.class'), jQuery checks all elements in the DOM. To evaluate $('div.class'), it only checks divs. So depending on the size of the DOM and the elements in it, the performance difference can be pretty significant.
So really, the pure CSS performance is almost exactly the same, but performance when run though a Javascript selector engine can be noticeably different. I think that is what I was aiming for when I asked this. Thanks to everyone for your comments, you all get upvotes :)

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