
Things to Avoid When Writing CSS - smpetrey
https://medium.com/@Heydon/things-to-avoid-when-writing-css-1a222c43c28f#.sgvlf0u3s
======
acjohnson55
Multiple files as an antipattern? Good luck with that.

If you use BEM, one of the many React style libraries, or any similar
methodology for simulating local scope, any big problems with multiple files
evaporate, and you get to reap the rewards of modularity. Granted, you still
inherit styles from parent document elements, breaking modularity a bit, but
for my purposes, it's close enough.

As a bonus, almost any perceived need to nest styles is also obviated.

On a side note, I found the tone of the article pretty obnoxious.

~~~
marrs
I think it's often an anti-pattern. A good acid test for me would be, will
modifying a rule written to a selector in one file affect a selector in
another. If the answer is yes, then you haven't modularised by definition; you
just think you have. This gets more complicated if you are doing SASS-style
inheritance between selectors.

~~~
gotchange
> will modifying a rule written to a selector in one file affect a selector in
> another.

Actually this is how it's supposed to work in terms of code reusability and
implicit inheritance. You change a detail in one dependency and that change
propagates through the chain to every other dependent object.

The trick is whether that change is intentional or not. When intentional, this
is a sign of a good architecture and vice versa and the poor performance can
be simply dealt with via good encapsulation to avoid future leaks.

~~~
marrs
The "good architecture" there is to begin by making things general and then
build specialisation on top of that. This is essentially what the author was
saying.

At that point its an implementation detail if you have your CSS in one file or
many. I think what the author is talking about is when you choose a module
structure that is orthogonal to that. That is the square peg that he is
referring to, by my interpretation.

------
thebouv
"Considering it’s a point of professional pride to avoid nested structures as
much as possible in other languages..."

Nested loops can be bad. Nesting logic deeply in other languages is bad.

Nesting style rules that belong together, well, together isn't nesting as much
as it is putting like stuff together.

I may create section.myawesomesection {...} and everything to do with the
stuff in there is in there, not leaking out. I don't accidentally use a class
name used somewhere else and globally change it, I don't change all global UL
tags to be flat, inline, no list-style. I change them in context of
section.myawesomesection.

Not to mention allowing me to put my breakpoints together in context
(particularly useful with a mixin like breakpoint(small) or something).

Yes you can really go nuts with the nesting and create a giant pile of crap.
But then that's you being a bad planner (not even going to say coder here, as
CSS/SASS is more about planning than coding).

~~~
stoikerty
I agree, nesting has been one of the most helpful parts in SASS to keep
everything organised. Nestin is just harder to do _right_ , you need some
experience in organising files.

Even with the specifity I vastly prefer nesting to a bunch of files with flat
selectors and a huge amount of globals where you need a lot of time just to
understand which elements affect which.

The post is quite opinionated and puts every issue in a bucket, as if there is
only one way to write CSS. A few examples would have been useful.

Not using Nesting is the worst offender in the list.

~~~
marrs
The trouble is that untangling nested selectors can be a real challenge,
especially if you have inheritance between them, and the implications can be
chronic. On a project I was working on recently, a colleague reported to the
team that the addition of one line of code to a SCSS file resulted in an
increase in size of the target CSS by 800KB. Looking at the spaghetti code
that had been written, none of us could work out how many rules were being
combined out of the deceptively clean looking SCSS.

A recommendation for that project was to lint for some ground rules forbidding
certain behaviours, nesting being one of them. I've actually been considering
avoiding SASS altogether in the future.

------
gotchange
I have to disagree with the first two points and concur with the last two.

Modularity can be achieved in CSS with ease (with Sass or any other capable
preprocessor) and I do it all the time and I haven't come across a problem
like he cited in his prose. The extended «@import» keyword/statement handles
this perfectly and you can do wonders with it, you just have to keep a mental
record of the hierarchy in your head (You already do that with the order of
<link> and <style> elements as well as the CSS individual rules within a
single file) and aim for well encapsulated components that are as loosely
coupled as possible to the surroundings in the markup and you will have a true
piece of mind.

As with nesting, yeah this could be a source of annoyance and inconvenience
but I usually set a ceiling of 3 levels deep maximum for any component with
rare exceptions when the need arises but most of the time I don't exceed the 3
level nesting limit and the codebase is still very very manageable.

~~~
emn13
The issue with nesting rules like "max three" is that you really don't want 3
levels of nesting, you _want_ zero. Setting an arbitrary cap isn't a bad
coping mechanism, but you might end up with pervasive low-level nesting, even
though you almost certainly don't need it.

In almost all cases I see, when people nest with SASS (or less), they don't
really mean "in this context, this item is styled like this", what they mean
is "this item only ever exists in this context". And if you use nesting for
_that_ , then you have at least one of three problems:

\- it might be entirely redundant - as in you get exactly the same style if
you just omit the surrounding selector blocks. This is quite common if you're
using classes heavily. \- it might be a "clever" way to avoid using a class
name. This is terrible idea; it's not clever to call something `.frugal > div
> span > span > b`, not even via nesting, it's simply undescriptive. Give the
beast a name already, and use that. If you're after this style, why not use
inline style tags? (No seriously - that's not as terrible as it sounds). \-
You've got too many catch-all selectors, and are fighting a selector
specificity battle. Nesting here is again a really, _really_ terrible
solution, because you've just made the problem that much worse. Nobody is ever
going to understand why the components layout breaks when they refactor if and
one layer is added or removed. If your style depends delicately on these kinds
of interactions, you're in a world of pain. Use @import, and consider
refactoring your usage of general or catch-all selectors.

I think its good advice to avoid nesting, especially more than one level of
nesting. It's never necessary (just use compound selectors instead), and where
compound selectors turn into a tedious, repetitive mess you've got techdebt
you should be resolving, not making worse.

Avoid doesn't mean "never use" \- but if your css has even one instance of
three-level deep nesting, I feel confident in suggesting that you're making
things fancier than they need to be. Nobody likes that programmer that left
behind his "clever" solution to save a few dozen keystrokes once, but that
needs lots of context to understand, and that's _exactly_ what nesting in SASS
is.

~~~
MatekCopatek
I find it funny that you suggest compound selectors as an alternative to
nesting, since nesting exists primarily to avoid the repetitiveness of
compound selectors.

I can agree that it might encourage some people to nest more then if they did
it by hand, but in my personal case, I was writing long compound selectors
already. The ability to nest only made the styling DRY-er and gave it visual
structure.

High specificity is definitely an issue that needs to be dealt with, but I'm
not sure the best solution is to stop using a feature that possibly encourages
it but also brings many other useful things to the table.

To end on a constructive note - don't forget you can use nesting to
concatenate string names as well. _.button { &-big {} }_ will produce
_.button-big {}_ , which means you can do some sort of visual nesting without
producing unnecessary specificity.

~~~
emn13
The issue with nesting to hide compound selectors is that it's papering over a
problem, not solving it. Hiding a problem tends to make it worse because it's
easy to ignore it, and easy to make it much worse.

Compound selectors are necessary for context-dependent styling; and all
compound selectors are context dependent. Nesting is equivalent. However,
context dependency makes it harder to reason about a layout, makes it harder
to refactor, and makes it harder to reuse parts elsewhere.

DRY-ness is vastly overrated in all programming languages; what matters is
composability. You're not writing a compressor. DRY is simply a means to an
end; being DRY helps composability because it means that changes to one part
of your program don't necessitate changes to the repetitive parts elsewhere.
If you _need_ to extract that commonality - of course, do so! But it's much
better if you can delete it outright, and in the case of SASS nesting that's
almost always the case.

For another perspective: every composition in a selector is essentially a
nested if in the "program" that is your styles. Do you really need nested ifs
all over the place? If someone changes the html structure a bit, are they
going to be surprised by which styles match if they fails to keep the styles
side-by-side? If you're nesting styles, your styles are likely extremely
tightly coupled with your html structure, and any changes that don't in
details dovetail with changes to the styles will cause unpredictable
consequences. If you're going to do that, consider something like
[radium]([http://projects.formidablelabs.com/radium/](http://projects.formidablelabs.com/radium/))
- i.e. inline styles. But you're probably best off combining that with
conventional styles for all the easy, reusable bits.

~~~
gotchange
> Do you really need nested ifs all over the place?

A maximum cyclomatic complexity level of 3 is rather acceptable and also the
technique of compounded class names you're pushing for is no different than
nested selectors since the same abstract logic operations, namely «if» and
«and», are at play too under the hood for both cases

> If you're nesting styles, your styles are likely extremely tightly coupled
> with your html structure.

That's the whole point of encapsulation. I prefer to draw the encapsulation
line at the component level not the sub-componenent level.

It's like an application of the "open/closed principle" where the component is
open for the outside world to be manipulated as a single unit but it's closed
and obscure from the inside.

This achieves in my opinion a greater degree of re-usability and portability.
You just import the component where you need it and apply the styles you wish
and then the component functions the same no matter where you place it because
of the loose coupling with the outside world and the tight coupling and high
cohesion inside.

However, if you'd like to carry out changes on a sub-component level and there
isn't any exposed interface already, for instance through a Sass mixin that
would allow you to tweak the inner parts, unfortunately you'd have to know
what you're doing whether on CSS or HTML front to make sure you are not
breaking anything and getting things done correctly.

To summarize, the main point of disagreement between me and you is where each
one of us would draw the encapsulation line, I prefer a more "macro" approach
while you're in favor of more "micro" and granular control over the building
blocks of your software which should work fine for either of us
simultaneously.

------
canyonero
This article demonstrates that the author has not worked a large-scale web
application. Modularity in CSS has been difficult to acheive, and there has
yet to be a perfect solution. However, I'll gladly work with an intermittent
solution. If I stepped into a project that followed these recommendations for
building an app of scale, I'd likely go insane.

~~~
bshimmin
People said the same thing - that the author had not worked on a large-scale
project - when he wrote this utterly insane piece about eschewing classes:
[http://www.smashingmagazine.com/2012/06/classes-where-
were-g...](http://www.smashingmagazine.com/2012/06/classes-where-were-going-
we-dont-need-classes/)

I think maybe he just enjoys being controversial. I have no idea how anyone
could really encourage multiple developers to work on a project with a single
CSS file - it seems practically almost impossible to me.

~~~
err4nt
I dunno, I write CSS for a living so I got nervous when I saw the title, but
when I read it I can tell this is advice from the frontlines.

This guys _understands_ CSS, and if you actually understand CSS you dont need
tools like SASS, and you dont need rigid structures like BEM.

The most beautiful (and seemingly ignored) aspect of CSS is that specificty
cascade. Everybody seems to be trying to isolate their CSS into modules so
they dont conflict instead of using the CSS together in harmony.

After writing thousands upon thousands upon thousands of lines of CSS here are
my quick opinions:

\- 1 global CSS files should take care of 95% of the styling, and if a
specific views needs to override that global style, give it a teenty tiny bit
of CSS

\- SASS is cool, but largely unnecessary, and so I believe that 80% of the
time people use it it just creates more work (learning curve, project
requirements, compliation step) than it saves. Again, I write CSS for a living
and I have never found a place where SASS sould have saved me work if you
actually know how to write CSS.

\- Nesting is awful, thats not how CSS works. I could abuse indents and
arbitrarily block my code in JavaScript and if I did that everybody would
assume I was an amateur who didnt know what I was doing. When I see nested CSS
I go on high alert for bugs because it is clear the author doesnt understand
CSS

\- while IDs and classes can be useful, So many frameworks now work in a way
that they write all of the styles you might nedd in advance and then you 'tag'
which elements get which styles ising classes. This is literally no better
than inline styles, and is an abuse of HTML in an attempt to not have to write
a small amount of CSS. If your markup is CLEAN and simplethen styling it with
CSS is also very straightforward. I havent read the authors piece but in the
past year I have noticed a drastic reduction in my own use of classes and
other identifiers in HTML as my understanding of more advanced CSS selectors
has increased.

CSS is a beautiful, POWERFUL language, and I would recommend everybody to do a
few things:

\- stop using CSS you didnt author

\- write your CSS by hand (no SASS, STYLUS, LESS)

\- Only ever copy-paste code youve written, if youre bringing external CSS
into your codebase, retype what you need from it.

I know those sound like youre going to be sitting there forever typing in
thousands of lines of CSS, but operating that way VERY QUICKLY forces you to
gain skill at discerning what is actually required or not.

Whenever I do responsive consulting I feel like most sites are 5x overbuilt in
the HTML, which means that your CSS is many many times longer than it needs to
be. The biggest bottleneck to CSS simplicity is poorly thought out HTML
markup.

~~~
bshimmin
Thanks for taking the time to write this longer response to my relatively
flippant one. It's also pleasant to see some positivity here about CSS, which
in these halls is often decried as being complete junk (rather unfairly - not
many things have stood the test of time so well, and remain mostly usable even
when applied in a wildly different context from their initial humble origins).

That said, I'm a little surprised you see no value at all in CSS
preprocessors; having spent over a decade writing CSS by hand (from the CSS 1
days), it was a moment of sheer joy when I started using Sass - probably more
than five years ago now - and discovered variables and mixins could be used
with CSS (and to a lesser extent nesting - though it's immediately obvious to
anyone who looks at the actual output or thinks for a moment about how this
works that it isn't a great idea to overuse it). I would find it very hard to
go back to writing raw CSS.

If you're working on a team of developers all contributing CSS to a project,
do you find that one CSS file is actually manageable? Do you not get merge
conflicts? Does it require vast discipline?

100% agree with you about the quality of actual markup in 2015. It's
miserable.

~~~
err4nt
> That said, I'm a little surprised you see no value at all in CSS
> preprocessors

I find value in CSS preprocessors in a few limited cases:

\- auto-prefixing for added browser support. Especially with CSS animations
this is one place where automatically generating the browser-specific CSS can
be a time-saver

\- for expressing design patterns that may be present in CSS in a more
succinct, clear way as a way of teaching or demonstrating a pattern to others

\- as a master copy to generate CSS that will be edited and maintained by
hand. Suppose I built custom WordPress themes for a client I could have a SASS
reset and base set of styles and then for each new project generate my CSS
file and go from there

> If you're working on a team of developers all contributing CSS to a project,
> do you find that one CSS file is actually manageable?

I am more of a responsive specialist so I'm usually brought into existing
projects where other programmers and designers have managed to get the code
into a knot they can't untangle, so I don't change the existing codebase
unnecessarily just to condense things, but for the project I author I will
usually deliver a global CSS file that includes all layout, typography, form,
button, and responsive styles, and then it's common to include an additional
stylesheet for each plugin you might be using. If you have a responsive table
plugin then it likely has one JS and one CSS file that need to be included and
I would link them in as external files instead of inlining them in my global
CSS. We then work with it as a team from there and it's been working well for
us keeping things more simple.

> Do you not get merge conflicts?

Working this cleaner way has greatly reduced the merge conflicts we used to
get when we were fully working within the 'Bootstrap' mindset and using
'classy HTML' and frameworks. Now we write clean markup, we pass over it with
JS and enhance it how we need and use CSS and a CSS polyfill that adds
element-based responsive queries as well as scoped CSS and the code is pretty
terse. Not much there to conflict with :)

> Does it require vast discipline?

Yes! But I'm surprised at how _little_ HTML, CSS, and JS is actually required
to build some really cool stuff. On thursday I was experimenting with the web
audio API and I made this teeny tiny HTML5 app that I bookmarked on my phone
and tablets and was able to play with over the weekend. It only took a few
lines of HTML, CSS, and JS to make a fully fuctioning web app - why would I
write more than I need to to do the same thing? I can iterate pretty fast when
I know how little code is actually required.

[http://staticresource.com/synth.html](http://staticresource.com/synth.html)

And that obfuscated blob at the bottom is nothing special, it gets unpacked to
become a set of instructions to build the favicon and app icon using a canvas
tag and attach it to the document. I encoded it using another teeny tiny HTML5
app I built
[http://staticresource.com/encode.html](http://staticresource.com/encode.html)

You can view the source code of these by using another tiny tool I built that
loads the requested page's source code and displays that instead. This way you
can 'view source' even when using your phone or tablet.
[http://staticresource.com/inspect?/synth.html](http://staticresource.com/inspect?/synth.html)

If I was trying to use React or Node with Bootstrap and jQuery for every
project I tried to build it would be a headache trying to build all these tiny
little tools and apps. No wonder people need all this crazy front-end tooling.
If you know HTML, CSS, JS, and learn the command line for manipulating files
and batch operations, as well as for ow to automate routine tasks you do
that's pretty much all you need in your toolbelt.

Whenever I work with teams I adapt to fit their pre-existing style decisions
and tools because that's part of what I'm being contracted to do, and I desire
to provide the most value while providing the least amount of friction.

Edit: and the significance of being able to build HTML apps so tiny is that
you can write them on the devices you use them on! These are entire apps that
you can sit down and write in Vim without it being awkward. I wrote this
little page to learn how to detect multitouch on my ipad one morning on
vacation. It's so simple:
[http://staticresource.com/touches.html](http://staticresource.com/touches.html)
I wouldn't have an easy way to write and test code using libraries on my
tablet, but I could write this and test it and I learned a lot. This is huge
considering Amazon just relased a decent tablet for $50, we can finally use
these devices for creative work building HTML5 apps and stuff is simple enough
now that just HTML, CSS, and JS is needed to build things.

~~~
bshimmin
Thanks for this response too! I don't have much to add other than to say that
you sound like you would be a pleasure to work with.

------
blowski
As the author says, in SASS, nesting that produces deeply nested selectors
like `body#homepage header .navbar:first-child li>a` should definitely be
avoided. However, you can do BEM style selectors quite neatly in SASS:

    
    
        .navbar {
          &__element {
            &__hover {
              ...
            }
          }
        }
    

which will produce a selector like:

    
    
        .navbar__element__hover { ... }
    

This is a great compromise between readability, maintainability and
performance.

Also, the first point about keeping all your CSS in the same file works for
smaller projects. But on bigger projects, managing a 5000 line CSS file is a
nightmare. Better to break your project into multiple files, and import them
as mixins or straight includes. Again, using BEM-style CSS helps with that.

In the end, managing CSS is always a pain whatever approach you use. Too much
of the advice on CSS doesn't talk about the context in which to apply or
ignore the advice. What works for for a massive team working on a high-
profile, big-budget, mission critical website will be enormous overkill for a
small project with one front end developer.

~~~
paulojreis
I like and use that way of writing compound, nomenclature-based, selectors in
SASS. There's a catch, though: you wouldn't find your style definitions by
searching via the resulting selector (e.g. .navbar__element__hover).

It's a smaller problem when you have the CSS split across files, but it's a
problem nonetheless.

~~~
blowski
True, and I've experienced that very problem. It's not a solution, but SASS
does at least output the line number of each rule set on the generated CSS
file.

------
Rezo
I've recently started keeping my CSS together with the UI components that I
create in React. Essentially doing what is being advocated here:
[https://speakerdeck.com/vjeux/react-css-in-
js](https://speakerdeck.com/vjeux/react-css-in-js)

It defies existing good practices, but once I tried it I quickly realized that
things that are tricky in CSS are mostly trivial in JS (namespacing,
dependencies, code elimination / minification, isolation, constants, the whole
tooling in general etc.). As a programmer and not a designer, I also find it
easier to reason about JS.

You end with something that looks very much like Web Components, but fully
usable right now. In practice it means you can add a 3rd party component with
"import TimePicker from 'material-ui/timepicker'", slap a <TimePicker/> into
your JSX and you're done. See [http://material-ui.com/](http://material-
ui.com/) for a complete toolkit of React components created this way.

------
poxrud
Using sass splitting files is not a big deal. The author is living in the
past, component based CSS is becoming the norm. For more info I'd suggest
reading about SMACSS by Jonathan Snook.

------
forgotmypassw
>A lot of web development seems to be about splitting things up into
manageable chunks or “components”. [...] This doesn’t work so well for CSS.

I'm not a web developer by any means but I'm pretty sure there's a way to
manage CSS "components" that then are compiled into a single, minified
stylesheet, no?

~~~
igvadaimon
I think what author meant here is order of those compiled files. For example,
when 'media_queries.css' comes before 'main.css', those media queries will be
most likely overwritten.

~~~
forgotmypassw
I understand that but there surely must be a way to account for that, I'd
imagine something like telling the tool to "don't override this section", or
"this one overrides that one, but not the other way around" should be an
option.

~~~
gotchange
This where the «!important» flag shines through but it gets a lot of hate in
the community but I am seriously not convinced with their reasoning and
arguments put forth as they seem not fully aware of the standard order of
conflict resolution in dealing with cascading and inheritance in the language.

~~~
d4n3
> as they seem not fully aware of the standard order of conflict resolution

I'd say it's the other way around - a lot of usages of !important are due to
lack of understanding of CSS specificity, usually as a symptom of something
else like using IDs in selectors..

If you avoid using IDs in selectors and avoid deep nesting of classes, then
overriding styles works as you expect - apply a more specific selector to
override the style.

Selector order only comes in to play rarely, and you can structure your files
to start with less specific (base) styles first.

I see !important as more of a workaround than a solution, and I don't think it
is used as it was originally intended.

~~~
gotchange
I was talking more specifically from a debugging perspective as most of the
frustration and anti-!important sentiment in the community stems from the
effort and time taken in the process to fix a layout issue only to find after
a half an hour of mental exercise and acrobatics an !important flag was raised
somewhere and hence was this unexpected layout behavior.

I'd say that people who debug this way are at fault here not the language
itself or this specific methodology followed because the order of cascading
and inheritance in CSS is as follows: importance, origin, specificity and
finally source order.

So, people who debug layout issue shouldn't jump first to diagnose specificity
problems but importance and to lesser extent the origin albeit it's less
common now to encounter a prob in this domain, and when everything is clear,
you go and inspect specificity and source order.

That's why I am not sold on the complete avoidance of !important when writing
CSS but I am of the opinion that you should only use them when necessary when
you need to override a certain style in a very specific context and not more.

~~~
d4n3
Chrome devtools sort selectors by specificity by default and you can quickly
see what order the selectors / properties were applied in and what overrided
what.

Most of the !important uses I've seen are more due to "Why doesn't this work?
Dunno, I'll just put !important on it.."

Since !important only applies to a specific property, it's not that useful for
making structured CSS components, and makes it harder to override (using
!important again on every property)

I can't think of many cases where using !important would be better than
overriding with specificity. Maybe when using 3rd party styles or making
styles that are embedded in an external page (e.g. widgets).

------
arnold_palmur
I prefer using rems over ems, as ems are a pain to deal with for large
applications (due to the nature of compounding).

~~~
emn13
However, rems don't compose as nicely. It kind of depends what you're
building. E.g, if you're in a footnote or any context where the font-size
differs from your general default, it's quite likely that whatever content you
want to embed there also needs measurements that scale - you want ems, not
rems.

The nature of compounding really shouldn't be an issue - because if that's an
issue, then your font size is going to be an issue in any case.

I'd say rems are appropriate when you're making a component that has little to
do with it's context. If you're conceptually emulating an iframe, then you
probably don't care about the scale you came from. Most pages have a few
components like this, but they tend to be the exceptions, not the rule.

~~~
arnold_palmur
Right right - I'm working on a large framework (built-in ember) where
everything is components, hence the appropriateness of rems.

That being said, I'm not sure I follow your example about the footnote - I
don't see any difference from what you are gaining with ems vs. rems as rems
are also going to scale. The scaling would be from the root vs. the parent
element which to me seems much more manageable allowing you avoid having to
calculate the result of compounding needed to achieve your desired font-size.

~~~
emn13
Well, if you're going to use ems, you probably should think about compounding
the reverse way - don't say, "I want X absolute font size, what scale do I
need", instead say "I want something smaller.

In the footnote example, imagine you'd want to include a button. That button
will contain text, and that text should be just as large as surrounding text
(or a bit larger - it doesn't matter for this case). You want to specify
button layout using ems so that the button is reusable both in the small-font
footnote context, and in the large-font body text context. Even moreso, if you
decide than the footnote font needs changing, your button will scale
naturally, rather than needing you to adjust the rem-based scale.

------
bbx
Multiple files

Considering everything is global in CSS, the importing order isn't important.
It only is when using Sass where you have variables and mixins that must be
defined before using them. And with Sass, it's very easy to setup separate
files that you import all at once in a single file. Structure example:
[http://tech.streethub.com/styleguide/css/app.html](http://tech.streethub.com/styleguide/css/app.html)

Nesting

One of the biggest issue you encounter when writing CSS is _specificity_. Not
only does nesting allow to match your Sass hierarchy with the HTML one, but it
also naturally creates more specific selectors that saves you from keeping
mind which rules are going to be applied.

Pixel units

Oh yes, using "em" is very elegant... but a pain in the long run. Font sizes
need precise pixels to render correctly. Images need pixels for alignment.
Borders need to be defined in pixels or end up disappearing. And you'll avoid
crazy calculations with 4 decimals. I actually just wrote an article about it:
[http://jgthms.com/in-css-use-pixels-not-em.html](http://jgthms.com/in-css-
use-pixels-not-em.html)

Device breakpoints

Breakpoints aren't meant for _devices_ but for your _element's_ size. It
doesn't matter how your layout will end up looking on a 320px-wide screen.
What matters is how your element will look like until 500px, and beyond that.
With Sass I have 2 responsive mixins: +from($breakpoint) and
+until($breakpoint). That's all you need.

~~~
zaphar
This is actually not strictly true and can trip you up if you aren't careful.
Two rules with the same specificity depend use last one wins. In that case
import order matters.

------
lsdafjklsd
The no nesting thing is huge! We refactored a lot of CSS earlier this year and
that was one of the biggest pain points. Coupling the structure of your
template to your CSS makes changing things very painful. Nesting also creates
ambiguous classes that have no obvious connection, consider the following:

.my-component {

    
    
        .header {
     
            ...
      
        }  
    

}

You would just see header floating around in the markup, unsure of where it's
namespaced.

Also I disagree that you shouldn't modularize your CSS. We now create a CSS
file who's name corresponds with the class name.

/styles

    
    
      /components
      
        my-component.css
    

and in the markup

<div class=".MyComponent-wrap">

    
    
      <div class=".MyComponent-title">  
        ...  
    
      </div>  
    

</div>

With CSS like that you always know where a style is declared, and the order of
the classes do not matter.

More on the issue: [http://nicolasgallagher.com/about-html-semantics-front-
end-a...](http://nicolasgallagher.com/about-html-semantics-front-end-
architecture/)

~~~
marrs
I tend to avoid nesting as well now.

Wrt your modularisation, that seems like a reasonable approach, although where
do rules go if you have nested components?

From my experience, modularity really starts to bite when you also have
inheritance.

For a simple case, you have a module A that contains class rules that are used
as prototypes for rules in other modules. You want to modify behaviour. Where
do you modify it, in the prototype or in the subtype? The answer isn't always
obvious and sometimes 2 conflicting answers can be correct depending on the
metaphor used for deciding how to modularise.

That's a simple case. A complex could be one where module A extends class
rules from module B and module B extends class rules from module A. What
happens when two rules extend each other? I've seen this in action, by the
way. The SASS compiled without error so one presumes that there is a limit put
on the recursion.

------
mdc2161
"Then, when I wanted to scale things up at a min-width breakpoint, I’d just
adjust the root font size, upon which everything else is proportionately
based."

The problem is that scaling everything up or down proportionally looks bad.
[https://css-tricks.com/rems-ems/](https://css-tricks.com/rems-ems/)

------
mosselman
There is nothing wrong with nesting in SASS. As with anything in life you just
have to keep thinking about what you are doing. Nesting too much or to deep
can make things hard to maintain or debug, but you can't say 'nesting is evil'
just because you think you are not supposed to like it.

------
Loque
The rationale from this post for not-nesting is incomplete and I personally
think nesting has advantages (grouping markup together and mixins for
example). Sure avoid the pyramid of doom and unnecessary nesting, but in
general, nesting is not bad.

Aside, BEM is a nice pattern but doesn't need to be followed religiously, you
could say the same for most patterns; put together the best for your
project/problem you are trying to solve... and if you have time, understand
all the design decisions behind a pattern in order to do so appropriately.
imvho

------
nitin_flanker
I have been using a percentage value to set width size for four year, since
the day I first used HTML. I used to get confused with pixel. Percentage
provides me a better estimate always.

------
rimantas
You won't learn anything useful from this article, move on.

------
stevewilhelm
It seems to me there is something wrong with a technology when how to apply it
in its most basic and fundamental use cases is so controversial.

------
auvrw
only recently started using less.js and thought nesting was helpful: i had a
not-so-well organized css file, and systematic nesting quickly enforced a
sensible grouping of statements.

also, if you want to change an id attr in your html, say, being thorough about
nesting ensures that you only have to change your styles in one place. that's
a small win for maintainability?

i agree that mixins are a much cooler feature of less/sass than nesting. it's
not so much that avoiding nested structures is "a point of pride" in general-
purpose programming languages (certainly not in lisp!) as it is that logical
modularity makes stuff easier to read, maintain, and reuse.

and as a practical matter, i can see how nested styles could make things
difficult to read if there are too many levels of indentation.

------
untog
I have to disagree heavily with the idea that all CSS should be in one file.
Therein lies madness. Use multiple files, and be _sensible_ about it - scoping
each file in a way that it won't overwrite other files.

------
TheAceOfHearts
I'm on mobile, so I'm unable to link to it, but Google CSS modules. Seriously,
it's a godsend for achieving true modularity.

------
k8tte
the author seems to be missing what HTTP/2 brings to the table [1]

#1: [https://http2.github.io/faq/#why-revise-
http](https://http2.github.io/faq/#why-revise-http)

