CSS coding techniques
hacks.mozilla.org
hacks.mozilla.org
Ehhhh, sometimes `!important` is a good option. I agree that just for the 'quick fix' it's a bad idea, but it can solve other issues beautifully.
For example: If you're writing a plugin or some sort of module that will inject a block of styled content in websites whose normal styling you have no control over, and you need to not accidentally let the sites override your own styling, it's a great fit.
In that situation, it's used to ensure that your block will display correctly across thousands or millions of websites and not fall victim to some awkward accidental local CSS rule like `#body #content #post strong {}` that some developer thought was a clever idea at one point, but didn't realize the implications of the insane level of specificity that is assigned. (I've seen this happen and the support load that it causes).
Far better to have reasonable selectors targeting only your markup, with `!important` so that sites, if they want to, can override your styling, but they just need to be explicit about it.
Long story short, rigidly holding to rules like these in /all/ situations can lead to far worse results for your users than taking them with a grain of salt and making educated decisions while understanding the implications.
> Ehhhh, sometimes `!important` is a good option. I agree that just for the 'quick fix' it's a bad idea, but it can solve other issues beautifully.
`!important` is the GOTO of CSS.
In general you're not supposed to use it, but if you do, it makes some things much simpler.
With style classes you don't run in to the issue of needing to then override the !important rule w/ another important rule - you would just remove the style class.
If you've reached the point where you know the right time to use !important, you probably already know its bad and most likely don't need any of this advice.
Yeah, and possibly break font-size and contrast changes for the visually impaired, if it's not scoped right - break printing ... in general I'd say you're more likely to create an issue than not, using !important.
Yes, if you are building something that should look the same across websites, this is a good idea.
Though it's often better to just have your own iFrames and use cross-domain communication, since your plugin will have to do its own authentication and API as well.
In my experience working with a lot of CSS frameworks there are times where not using !important would make the site too brittle if layout had to be changed.
When it comes down to abusing selector nesting vs using !important, use !important.
If you're writing a module, best to prefix each class with some abbreviation. `#MyModuleName .mmn-foo` ... much less likely to clash, still need the `#MyModuleName div` reset, but it's better than dealing with weird integration issues.
If you'd like to go a step further, I really recommend this[1] CSS style guide by the folks at Trello. I try to use it on all my projects. It makes working with CSS so much easier in my experience.
That's very strong wording, and I couldn't disagree more. I've added in-line styles into my React workflow for several projects and couldn't be happier with it.
To me, React is primarily a tool that lets the developer define their view in terms of their model, separating business logic from display. Styling is a part of that view. Class names are just an extra abstraction between the view and the model, and offer little benefit.
I like the idea of purist separation of "style" and "view" but it's unrealistic to think it needs to be a point of dogma.
There are clearly cases where you would want most your styling to be separate, particular for client-specific branding, but there is likely "functional" css such as css that gets date pickers etc working and those can't really be cleanly separated from the view.
A lot of CSS isn't really "style", it's actually far more functional than that. Try turning off CSS and see what happens to fancy date-pickers or rich text editors or other controls, they don't degrade cleanly they just break.
(to be fair, React doesn’t seem to solve more problems for me than it creates - quite the opposite - so I’ve never built anything past toy apps in it)
... which you can just as easily do in React. It's JS after all, so you just use JS modules -- and I hasten to add that there are probably-better-than-plain-JS solutions out there[1].
[1] Here's one example: https://github.com/gajus/react-css-modules . (Dislaimer: haven't actually used this, I'm using scala.js)
There needs to be a happy medium. Projects that go to extremes to decouple everything are
a) a waste of much effort for little gain. b) as big a pain to work with as code that is completely coupled.
I think what that line is trying to convey is that you shouldn't be doing things like adding a script tag that goes in and sets all classes to have "background-color: red", and to try to avoid using JS for animations/transitions where possible.
Just like when someone says don't HTML and JS, they aren't talking about JSX most of the time.
What do you thinks, guys?
Edit: Meant `js--on-hover-this-element-do-display-block-other-class`. Obviously, other class would be an element with `.other-class`
Is this a joke?
Of course it's a joke. Use semantic CSS class names.This is border-line Poe's law; I really had to deal with web-3.11-for-workgroups folks who argued that this style is the way to go.
Never felt this good to realize to have been tricked 8)
How does this approach deal with themes? How can I redesign a page without editing all HTML?
SharePoint's markup is rad. /s
But I'm okay with it either way. We'll still have to help people figure out where master pages / page layouts still fit in, and we will (hopefully) have an easier-to-reason-about path to use React or whatever other framework with SP in a supported way.
!important isn't intended as a workaround for your own code. It's for an external asset to override an internal one.
With CSS modules you don't have to think about whether you're being too specific or whether your styles will have side effects, because all of your CSS is locally scoped to just the component you're working with.
Disclaimer: I wrote it :-)
I see a lot of people using classes to create unique styles for specific elements. This will make a mess of your stylesheet.
Also try not to think too much in subcategories (nested classes) because it will remove flexibility from you stylesheet. For example:
.button {}
.button.text-center {}
is used to create buttons with centered text. But now you need to create another class for other elements that need centered text.
So instead this would be more flexible: .button {}
.text-center {}
In both cases you can use <element class="button text-center">.If you're stuck using vanilla CSS, that's probably the best you can do. But if you have a preprocessor that allows mixins (and god, you really should), I find life is made infinitely better if you have very specific class names, ie. every element with a given class name should be styled exactly the same.
Any styling that's shared across multiple classes (both in the literal sense of a selector, and in the sense of "grouping of alike elements") belongs in a mixin that gets mixed in appropriately.
If you're certain that's unique, you can use ids if you like, but I don't really see the point. Plus, like all feelings of certainty in programming, the future will love mocking you for having it.
(On reflection, the same frequently applies to OOP classes...)
On the other hand if this would be an overkill ( small landing page ), then basically whatever you would choose it would be okay, because rewriting the stylesheets will take less than a day.
If the requirements doesn't allow that and you are building a huge complex UI, then I would advise >against styling tags<. There have been at least 100 times in my career, where I discover someone styled an `a` element, that I would like to become a button. My approach is to use class names everywhere.
It may be a 'bloated framework' but it works and I've spent enough time on CSS already.
I hope that time wasn't spent customizing Bootstrap to your liking and requirements - you could have worked on your very own and much more lightweight set of common CSS rules instead.
I'm sorry but how anyone, who is at least moderately experienced in web design, could use massive CSS frameworks like Bootstrap or Foundation for anything but quick previews and basic demo apps is beyond me.
Cleaning up my code last week I decided to remove it from my source folder to see what would happen. Gulp did its thing, I hit refresh and my app looked exactly the same.
The CSS I added on top of Bootstrap removed the need for 160ish kb of styling rules and gave me full control of the look of my app. No more "col-sm-6 col-md-5 col-md-offset-2 col-lg-6 col-lg-offset-0" nonsense and no more wrestling with the framework.
A day learning CSS basics, Flexbox, Psuedo-elements and best practice brings big returns. And more importantly, gives you design control over whatever you're building which makes prototyping super easy.
In general, I have been happy with making a little style file that grew up to 300 (I think) lines or so over that last almost a year. This approach (not using a mystery CSS file) also paid off when we had to make a custom page with alternate styling for embedding within another app.
Now if only CSS selectors were as full featured as XPath :-)
- Only use cascading for global theme styles, like type faces
- Don't nest rules with sass or w/e, it's too hard to know what's affecting what in a template
- Naming conventions: Prefix every component class with the titlecased version of the name, have one css file per component that's of the same name. This makes it easy to know where to look for styles when you're working in a template. e.g. styles/header.css would contain:
- .Header-container .Header-link .Header-title--hover .Header-imageOf course, I know in the long run, that will lead to even more bugs but I don't have an effective workflow around that.
1) use a prefix (t-) for test selectors and do not attach any styles to them (put them on the elements you need to target directly so the tests do not have to know about the DOM structure)
2) use data- attributes for test selectors (again directly on the target elements so DOM changes won't break the tests)
The second I got from this article, which is a bit Ember specific, but makes a lot of good recommendations:
https://dockyard.com/blog/2015/09/25/ember-best-practices-ac...
Thanks for the suggestion on how to work with test classes anyway. Very useful.
[1]: https://github.com/BBC-News/wraith
[2]: https://percy.io/
!important should be banned. !important divides the good guys from the bad guys. Whenever I see code with !important I instantly know that guy was lazy, unexperienced, wrong guided - you name it. And it also makes my life hard if I have to continue to work on that same css.
I also miss one of the most useful methods to be more granular with the cascading. To apply a new rule, instead of using a fresh new class or to hammer into some new style definitions with an id/!important just use the class twice in your css. More of the same class means more important.
.button.button.button outranks .button.button which outranks .button.
See here for an example:
http://codepen.io/gkey/pen/ONevEeIt's not beautiful and if you're doing css right you won't need it most of the time. But try this before using the big bad boys like an #ID or the !important statement.
In 90% of situations, the [avoid !important] rule is a good one. By and large, we’re much better off following it than not following it. But there will definitely be situations that fall outside of that 90%."
Sooooo, I guess 10% of the time he's driving dying people to a hospital. DON'T TAKE DRIVING ADVICE FROM AMBULANCES!!!!!
Various other scenarios similar to above is not uncommon for frontend developers to find themselves dealing with in the workplace.
Your narrow mindedness on the scope of issues that could be at play makes me doubt your abilities.
[EDIT] I am slightly jesting by reflecting your comment judging others based on few factors
As such, it has legitimates uses in rare cases (a responsive websites with some javascript style changes specific to a breakpoint per exemple.)
I would personally say that what divides good and bad guys is opinionated though.
.buffalo.buffalo.buffalo
yes?This is even crazier than using an "!important" once in a while. You're creating obfuscated CSS that technically respects the concept of cascades and specificity. Yet your reason for doing this is essentially just to avoid "!important", while not actually fixing your cascading/specificity problem. I'd rather see the rare "!important" as a visible warning sign that something was lazily patched, rather than a poor workaround that is invisible.
This kind of solution sounds a lot like I get in trouble for using "!important", so I'll use an alternative dirty hack that is hidden well enough that I probably won't get caught.
When you're already reflecting about !important, well then you're happy to use it, because you think and know about all the consequences. HN readers reflect a lot. So you're clearly the wrong audience.
I'm sorry for my harsh 'lazy and not so experienced' expression. But sometimes you have to exaggerate to be heard.
Those developers I'm talking about just don't think about the consequences. !important is not a tool for them, it's their last resort to fix something. And then? Well it's a dead end and the rise of all the problems with !important we are talking about. If they would know about chaining, they would have used chaining before using !important. It would be a mess too. Yes. But at least it's not a dead end for them and for any other developer who have to contribute to the same codebase.
Where as a rem would always be relative to the root of the document, which is not always the desired effect when it comes to responsive typography.
If i set the HTML font-size to 16px (the default) the widgets are WAY too big, if it set it to 10px (what they use in their examples) it looks great but everything else is too small.
So I need to either re-style all the widgets (damn near impossible), or set all other elements to 1.6rem...
If they used em, i could just set the container to what I wanted and called it a day.
So em definitely has it's place, but I think the majority misuse it.
Everywhere else, I'll just use pixels.
I use .flat { margin-bottom: 0 !important } to remove the default bottom margin from certain typographical elements (ie. h1,p,ul). In this case where I absolutely know that I mean what I say when I apply that class, it works great.
.flat.flat.flat.flat { margin-bottom: 0; }
It gives you the specificity to override most things, and still leaves you the "nuclear option" of `!important` if you ever need it.I love using SASS to generate my CSS, and I recently started using bourbon and neat with my Go project.
I ran into issues as I did not want to use gulp or grunt so I put together my own way using a Makefile
<div class="block block__element block__element--modifier"></div>
Is there some good reason people write that instead of just the following? <div block="element modifier"></div>
Unless I'm missing something, with the second approach you get the same specificity, higher flexibility and shorter and more readable markup. Moreover, you end up using selectors the way they're intended to use.I reached BEM via AirBNB's CSS style guide - to me the real value in these style guides is I don't have to care about formatting CSS, JS etc anymore.
If you are reduced to needing to use either of them, it means that your CSS had gotten out of hands and you are trying to apply band-aids.
If you ever need to use !important or an id to fight selector specificity, take a step back and rework all your CSS.
Source: 5 years of not using either of those as a front-end developer.
Component thinking is good, it's CSS "best practices" that are backwards and insane, probably because many of the people who came up with them were designers who weren't educated in the basic principles of writing maintainable code.
You do not want to be in a situation where, when you change a particular class, in order to fix a bug in one UI element, it potentially has side-effects in a myriad of others, none of which you know about.
You do want to be able to come into a codebase and make a fix to a particular element, or component, in your UI, and have absolutely confidence that you have not broken anything else.
How do you do that? By breaking down your UI into independent, encapsulated and composable components. And the component's styles should be specific and encapsulated in the same way as its JS code would be. The fact that CSS allows you to create a big stew of global variables does not mean that it's a good idea to do so. Anyone who tells you otherwise is misleading you.
Follow this "be as unspecific as possible" advice and I guarantee that in a year or so, your CSS will contains thousands of low specificity rules, all applying randomly to different bits of your DOM, with thousands more specific classes to override the unwanted styles that are being picked up from elsewhere.
I feel like the term "coding" should be reserved for writing code that will be compiled. Anything that's not compiled (but is still Turing complete) is "scripting". CSS, HTML, etc. is just "tagging".
"What?" - Everyone
Not sure that this matters except to preserve some "purists'" (read: pretentious engineers') holy lands. CSS is code. Writing code is called coding.
I don't think it should be called programming, though.
So you're suggesting that the term programming be used to describe writing code that will be compiled?
I really don't care though. Call it whatever you want as long as I can understand what you're trying to say. "Tagging" doesn't satisfy that sole requirement.
Higher level languages help you abstract things more easily. Of course you can make any arbitrary distinction you want between languages and runtime systems, but to what purpose? And even if you were to make a distinction like you have made, where would you draw the line? Is compiled byte code that is run on a VM "coding" or "scripting"? What about tokenized languages that are simply executing lists of precompiled tokens? What about threaded interpretive languages that compile down to jump tables?
Besides, CSS is an excellent example of a declarative programming language. I don't even know that it is not turing complete. I rather suspect it is, actually (though not in any useful way). Writing CSS is programming... just in a different way.
Different kinds of abstractions are useful for creating elegant designs. Programming is young so we only have a few abstractions. It behoves the good programmer to learn how to use all of these kinds of abstractions appropriately. Each is powerful an beautiful in its own way.
More discussion of that and a jsfiddle demo: http://stackoverflow.com/a/5239256
I feel that the root of my frustration with HTML/CSS is that it enforces a specific design pattern (that of boxes and inheritance) that is so bulky and unintuitive.
But I do agree with previous commenters that it seems like splitting hairs to declare web stuff not "coding". In practice, you would very much like a "coder" (someone with a CS background/education) to be handling your HTML/CSS, then have a lay person doing that work.
The compiled / interpreted distinction is sort of unimportant - I certainly wouldn't refer to myself as a "Python programmer", because all I do is use matplotlib to make figures for publication, but the guys and gals who wrote matplotlib are most certainly "Python programmers" in my book.