Settings

Theme

Principles we use to write CSS for modern browsers

gist.github.com

184 points by vuknje 9 years ago · 128 comments

Reader

skrebbel 9 years ago

A bit meta, but I need this off my chest: I love how this document starts off saying "this is for react apps". IMO every discussion about CSS coding standards needs to start with context.

A lot of old CSS lore came from people who build websites. I mean those fairly uninteractive things, focus on content. Blogs, restaurants, newspapers.

Building an application that happens to use the DOM as their UI toolkit is totally different. The whole "reuse the same classes but with different content" thing that CSS classes were designed for becomes less important, and "reuse pieces of behavior" makes a lot more sense.

There's probably more domains or subdomains that warrant their own CSS best practices. But I'm totally tired of a blog designer and a react app coder fighting on HN about how the other one is doing it wrong, when really they're just solving different problems.

  • Wintamute 9 years ago

    I build large static websites, and sometimes apps, and can confirm that the CSS techniques listed in the article work very well for both use cases.

    UI components don't need to map to richly interactive parts of an app, they can just as appropriately map to repeated design elements in a well planned static site.

    To me its the same problem.

  • sanderjd 9 years ago

    Well said. This goes (probably double) for the similar conversations about javascript, where lots of people question whether it should be used at all, which is a reasonable question for sites but not for applications.

    • threesixandnine 9 years ago

      Those people probably have static content sites with lots of js on their mind when they say that, no? Ads, tracking code, etc....

      • sanderjd 9 years ago

        I think they probably do, which is why I really liked the parent comment about how people should be clear about what they're talking about so that we stop talking around each other all the time.

  • talmand 9 years ago

    "reuse the same classes but with different content"

    What difference does the content make if the styling is meant to be the same?

    "reuse pieces of behavior"

    Now, that made me curious. Can you expand on that because I'm not sure I quite understand what you mean.

    edit: I've read through the naming convention they describe and I don't see much anything that different than how I would create CSS for a website. It's just a clean naming convention that would work for a website as well as an application.

    • bobbytherobot 9 years ago

      I think "content" should be "context". It is when you create a class based on appearance instead of context. To make it worse, is when the class has a semantic name like Hero but it is being used in clearly non-Hero usages. It makes refactoring hard.

      • talmand 9 years ago

        Ok, sure, I see what you mean. But I put that under "not using tool correctly so blame tool" category.

  • ooqr 9 years ago

    I would love to read a long-form article about this if you're ever inclined.

    • skrebbel 9 years ago

      I'm flattered, but I'm not sure I have much more to add! What would you expect to be explored more deeply in such an article?

      • ooqr 9 years ago

        I just haven't encountered this problem yet as a junior dev and would like to learn more. Perhaps it will just come with more experience.

MatekCopatek 9 years ago

IMHO, naming conventions such as SUIT, BEM, OOCSS and the like are NOT a good practice, but merely a workaround for dealing with the limitations of a global namespace.

My preferred solution are CSS Modules[1], Vue's scoped styling[2] or something similar.

[1] https://github.com/css-modules/css-modules

[2] https://github.com/vuejs/vue-loader/blob/master/docs/en/feat...

  • PaulHoule 9 years ago

    What amazes me is how violently the run-of-the-mill programmer hates namespaces. Despite the fact that managing namespace collision is important for composability (either deliberate or accidental) and code generation.

    This problem has, for instance, dogged RDF. All the time I hear about programmers who "don't want to learn SPARQL" and I think the heavy use of namespaces is one of the impediments. For most other programming languages it seems the opposite:

    (i) half of the software managers in the world are driven nuts because their team is screwing around with Vagrant instead of working (ii) it seems no programming task is too boring if you do it in rust or go.

    • sjclemmy 9 years ago

      That reminds me of a colleague complaining about a recent cohort of about 60 webdev graduates. Not a single one wanted to learn perl, but were quite happy to get stuck into anything Javascript preferably react!

      EDIT: why the downvotes?

      • rfrey 9 years ago

        They're quite rationally looking for assignments that increase their own market value.

        • eonw 9 years ago

          learning backwards can be good too.... i know a guy making $200k+ managing some old AS400s, part time, and he is too young to have grown up working on them. old school skills are worth money, and the unwillingness of new entrants to learn them just makes them that much more valuable.

        • PaulHoule 9 years ago

          I haven't done anything in Perl since 2005 or so. I think it got eaten pretty much by Python, PHP and Ruby.

      • wvenable 9 years ago

        I've worked in enough Perl at one point to actually like it but I would never recommend anyone learn it unless they absolute have to. At this point it's effectively a dead ended language. It's also a terribly difficult language to learn.

        I don't particularly like the Javascriptification of every technology but these webdev graduates have the right idea.

        • eonw 9 years ago

          i didn't find perl terribly difficult to learn at all, but then again i learned it 12-15 years ago and maybe it was more on par with other languages at that time. don't think i would want to learn it now though, still have a strong appreciation for it though.

          • wvenable 9 years ago

            Perl is full of strange grammatical rules and even stranger conventions that it's one of the few languages I learned 15 years ago that I can't just pick up and use. I've forgotten basically everything I ever knew about it and yet other languages from the time period, even some odd ones, I can still grasp enough to restart the process.

      • sotojuan 9 years ago

        If I was studying web development in 2016 with the hops of getting a good job, I'd also stay away form Perl and learn JavaScript.

  • davidkpiano 9 years ago

    CSS Modules is still a "naming convention," just one that is auto-generated for you. Naming conventions in CSS are as much of a good practice as naming/linting conventions in JS.

    • vinceguidry 9 years ago

      Auto-generation is a good solution because names are the brain's interface to the code. If the names are auto-generated, and the brain doesn't have to look at the auto-generated names, and the abstraction doesn't leak, then you can consider the problem solved.

      • Jasper_ 9 years ago

        My devtools still doesn't show me the unmangled name. The abstraction leaks.

        As a practicality, I prefer the naming conventions to the CSS processing pipeline, because it gives me a much better ability to debug and iterate.

        • Klathmon 9 years ago

          With sourcemaps you can get close, but it still shows the "mangled" class name in the HTML.

          But with a dev/prod environment, you can have your cake and eat it too (for the most part). In dev we have our classnames be in the format of `[classname]---[file-path]---[filename]---[partial-hash]` So one of my classnames from a current project is `.container` in the file, but shows up as `.container---src-components-scanner----styles---1446d`. And in production shows up as `._1533JgnvGu096C2bCAkrxT`.

    • philh 9 years ago

      It looks like CSS modules is meaningfully different from being just a naming convention.

      With a naming convention, if you want to use work from two different packages and they happen to use the same names, you need to edit one of them. People come up with conventions to try to avoid this, like prefixing everything with the package name, but that doesn't fundamentally fix the problem. If two packages have the same name, they clash again. You have a fundamental tradeoff between short prefixes which are easy to work with, and long ones which are less likely to clash.

      In other systems, when you use a package, you choose the prefix. If two packages use the same names, you just give them different prefixes. Short prefixes are fine, because they don't need to be globally unique.

      It looks like CSS Modules works the second way, and that's an improvement over just being a naming convention.

    • MatekCopatek 9 years ago

      I agree with vinceguidry's comment.

      Perhaps I wasn't clear - of course you should be careful about naming things well (one of the hardest problems in CS, right? :P), but using consistent terms, case and the like is one thing.

      A large part of CSS naming conventions is doing more convoluted stuff such as business-page__contact-form__submit--disabled, just because there are other submit buttons on your website and you don't want some styles to clash. This is the part that is abstracted away by automatic solutions.

      If your favorite programming language scoped all variables globally, no matter where you defined them, sure you could prefix them with the name of the current function to solve your problem, but it'd be painful and error prone.

    • lisper 9 years ago

      > CSS Modules is still a "naming convention," just one that is auto-generated for you.

      Yes, that's true, but your use of the word "just" implies that auto-generation is a detail. It's not. It's the the big win. At root, everything is machine code, which also has a flat namespace. Having that flat-namespace code auto-generated is a huge lever.

      • Klathmon 9 years ago

        And it fixes a few other unexpected problems as well.

        We use SHA1 hashes of the CSS classes' contents as it's name when using CSS modules. This has the cool side effect of making any 2 classes that do the same thing to have the same name, and get de-duped in the final output, regardless of where they originated in the application.

        When I saw it happen the first time, it really kind of cemented in the idea that this combined with a way to "punch through" the modularity to combine and extend "base" classes and include global colors (for us it's SASS imports) has pretty much "solved" CSS for me.

        • breatheoften 9 years ago

          That's a nice trick -- thanks for sharing! Am I write in understanding that implementing this within webpack is simply using only [hash] as the localIdent configuration property for css-loader?

          • Klathmon 9 years ago

            yeah, specifically [hash:base64] because [hash] will print the hex of the hash which is a bit more verbose. I think it's actually the default for css-loader if you don't set localIdentName

            During development we have it set to `[local]---[path]---[name]---[hash:base64:5]` which gives massive verbose class names but lets me pinpoint exactly where they came from.

            There's also one step that I left out that helps, which is to have something like csscomb[0] to order the properties of each class into a set order. It really lets this optimization shine by ensuring that different property-order won't cause different hashes.

            [0] https://github.com/csscomb/csscomb.js

        • lisper 9 years ago

          Neat trick, but SHA1 is serious overkill for this. Even MD5 would be overkill. You don't need a cryptographically secure hash if you aren't dealing with inputs controlled by an adversary.

          • Klathmon 9 years ago

            Yeah it's overkill, but it ads basically no extra time to our build, so there's no need to optimize it.

  • cel1ne 9 years ago

    My preferred solution is http://tachyons.io because it has a font relative scale for spaces. No more guessing of pixel values.

ulkesh 9 years ago

Some thoughts:

- Good CSS design needs zero !important statements. Fix your specificity or your component architecture if you have a need to use !important.

- DRY is a good thing, not a bad thing. Maybe straight CSS isn't quite there yet but...

- Why not use the tools at your disposal to aid in development (and DRY) such as SASS/LESS?

- Flexbox will be great once IE dies the well-earned death it deserves.

I'm very happy the author had great success with their setup. What works, works. But I hesitate to assume that just because it works without using DRY principles or other tooling, it means you shouldn't.

  • MatekCopatek 9 years ago

    Avoiding !important is generally very good advice, although the ZOMG NEVAH! approach is a bit overzealous IMHO.

    One good example would be overriding random external styling (e.g. an included CSS file some plugin you use). If their stylesheet has very long and specific selectors, you can either repeat them entirely (#plugin .container .subcontainer .input-wrapper.input-wrapper-blue input[type=text]:first-child) or stay within your general selector-writing practices and use !important instead. I'd argue the latter is a better practice.

    • ulkesh 9 years ago

      I agree with respect to 3rd party libraries. One of the things I hate most about Bootstrap is its amazing overuse of !important.

      However, my context was mainly around architecting your own CSS, not as it relates to using someone else's.

      • atomwaffel 9 years ago

        My approach is to slap myself in the face each time I need to use !important. That's enough to prevent me from slipping into bad habits but leaves me with an option if rewriting my CSS to work around somebody else's (or my own) hacks would be more painful than a slap in the face.

        I do occasionally get strange looks from my colleagues.

        • talmand 9 years ago

          Just wear a rubber band on your wrist and snap that instead. Your colleagues will just think you're trying to stop smoking.

          • mst 9 years ago

            Or get a pavlok (I have one, it's rather neat, though the bluetooth is predictably terrible).

  • adregan 9 years ago

    Secretly, I'm not that happy with flexbox. I think it's more intuitive in some cases, but I don't think it's more intuitive than floats and the like.

    For example, I always feel like I want a `justify-self` property like `align-self`, but instead I must use `margin: auto` on the opposite side—in a flex row of elements, if I want the last one to be right aligned while the rest are hanging out in the center, I have to tell that last element to be `margin-left: auto`.

    I think it's just an issue that it has taken so long to be useable (IEs :( ), there has been a lot of hype, and it's not quite the panacea I imagined it would be.

    • ng12 9 years ago

      I agree that flexbox isn't particularly intuitive. I visit the "Complete Guide to Flexbox" at least a few times a day.

      The real strength is how little of it you have to write. The most complex layouts I have only take a few lines of flex and they're way more responsive than their non-flex counterparts.

  • dclowd9901 9 years ago

    Using !important is often encouraged for state changes (e.g. ".is-showing" etc)

  • gbog 9 years ago

    I'm surprised there is no polyfill-like thing for flexbox, or is there?

    • skrebbel 9 years ago

      Can't be. Hm maybe with lots and lots of JS moving stuff around with absolute positioning, but otherwise you simply can't port flexbox to older css.

      • ng12 9 years ago

        There is a JS polyfill. It's relatively popular, but I've never tried it. https://github.com/jonathantneal/flexibility

        • ry_ry 9 years ago

          I'd be hesitant to use that in prod code - realistically you can achive fairly graceful degradation without it as long as you're prepared to accept a non pixel perfect layout.

          Also, from the issues v2.X that polyfill appears be broken in IE9 atm, which is the last one with zero flex going on. (Fun fact, our metrics have ie9 and 10 with comparable userbases - fairly standard large public facing site. 9 is fully unsupported and IE10 is no longer an active target for our QA team beyond basic layout and functionality)

          I do generally use a less mixin to shim all the tweener syntax tho.

        • skrebbel 9 years ago

          Oh wow! Awesome, wish I knew before. This blows my mind, thanks!

  • caub 9 years ago

    css variables too

  • daurnimator 9 years ago

    > - Why not use the tools at your disposal to aid in development (and DRY) such as SASS/LESS?

    Because there is so much tooling churn + barrier to entry. The point is that sometimes it's better to repeat yourself than to use the tool of the month.

    • shabda 9 years ago

      Both the tools mentioned above LESS/SASS have been for 5+ years. There is churn in frontend tooling, but it is not a valid reason for not using LESS.

    • t4nkd 9 years ago

      Usually this kind of attitude could be justified even if it was just a shitty anecdote, but with SCSS and LESS in particular I'm afraid you've chosen long lived, bulletproofed software that has tremendous adoption and community. Neither would be what anybody would call "the tool of the month".

    • Tloewald 9 years ago

      If you're using React but not LESS or SASS then you have a strange attitude to "tool of the month" but it does explain antipathy towards DRY.

    • andruby 9 years ago

      SASS is almost a decade old [0] and has been in wide-spread use for a long time. The tool churning you talk of is something I have only seen in JS land to such a degree.

      Moreover, the barrier to entry to learning SCSS/LESS is really low if you know CSS.

      [0] https://github.com/sass/sass/tree/4acf5158734013f08fca4be6e2...

    • exceptione 9 years ago

      Both are proven tools and should be used by any serious frontender. Pick SCSS, it's your most advanced option; you won't hit a limit in what you ultimately want to achieve.

al2o3cr 9 years ago

".ComponentName-descendentName" nested inside ".ComponentName"?

Remember kids, the cascade is TEH B4DZORS - so always include everything you would have gotten from it in every class name. headdesk

Solidly delivered on the "no DRY" premise. Maybe they should coin a new acronym like "WET": "Write Everything Thrice"

  • awesomebob 9 years ago

    CRY: Continuously Repeating Yourself

    WET: Write Everything Twice

    Credit: https://roots.io/sage/docs/theme-wrapper/#fn2

    :)

  • spdustin 9 years ago

    > "Write Everything Thrice"

    Solid. I'm using that in my class today.

    I love React, and even there, I only style components in the way they need to be styled, and not with any other brand-specific styles. Those go in the good ol' fashioned CSS with "gently nested" CSS selectors. The enterprise world is considerably more nuanced than many SPA devs understand.

    A class of folks from US Gov, manufacturing, pharmaceutical and finance industries (to roll them into general groups) and every one of them answers "IE9" when asked what browser they have to support, and every one of them is at home with "the old ways" of writing CSS, by embracing the cascade.

    It's not that they're wrong. They're pragmatic.

    And, In some cases a little bitter, I'll grant you. ;)

  • vog 9 years ago

    I propose to name it the "wet-wet-wet" principle.

  • Guillaume86 9 years ago

    The whole point is probably to avoid cascading and issues it creates when you will start to nest different components.

  • Roboprog 9 years ago

    We Enjoy Typing is the explanation I usually see.

andybak 9 years ago

A random brain dump prompted by this statement: "No DRY. It does not scale with CSS, just focus on better components"

All programming involves resolving a conflict between two different principles and a lot of the fiercest disagreements are between people that weight the importance of these two things differently:

1. Reducing repetition

2. Reducing dependencies and side effects

The language and it's tooling/ecosystem can affect the importance of these.

The project's complexity, rate of change and lifespan is also a factor that might push you one way or the other.

But anything that helps one of these harms the other.

Thoughts?

  • MatekCopatek 9 years ago

    I wouldn't say that they are always mutually exclusive. I think there is a variable ratio between advantages gained by 1. and disadvantages caused by 2.

    In other words, at first, reducing repetition will net nearly no negative results - you just recognise different areas that do very similar things and write a common functionality. The most basic example would be programming languages providing standard libraries, even though everything could be done with regular operations. At this point, abstractions are even simpler to use than implementing things yourself.

    Problems start to arise once you hit a certain point beyond which your abstractions become harder to use and maintain than simply writing things multiple times. This is where you should stop abstracting/modularising things away (assuming that the reason is purely overengineering, not bad engineering).

  • brunoc 9 years ago

    That's consistent with my experience with a very DRY Sass library. If the consumer needs flexibility, such as different themes or new context for components it quickly becomes impossible to manage dependencies and abstraction begin to leak.

    CSS tooling is quite rudimentary, too, which doesn't help.

  • adrianratnapala 9 years ago

    You are essentially right. But I would say anything that helps one of these harms the other.

    Part of the art of good language/library/thingy design is to understand, and then defy those trade-offs. Try and have you cake and eat it too. It's not always possible, but sometimes it is.

davedx 9 years ago

> Flexbox is awesome. No need for grid framework;

Yes, great, if you can ignore all the IE users. Is that what "modern" means?

I'd love to use flexbox where I work, but it's just not feasible to give up all the customers we would lose.

  • freshyill 9 years ago

    Why not both? Global flexbox support is >96% and in the US it's >97%.

    Unless you're aiming for a 1:1 pixel-perfect experience in crappy old versions of IE, it's negligibly simple to detect IE (or lack of flexbox support), and just use something else. You can usually get pretty close to a lot of flexbox layouts with display: table and related properties, and also falling back to floats for others.

    In a worst case scenario, you can provide old IE with a more mobile-like experience and just let things stack up.

    • spdustin 9 years ago

      Enterprise in the US. IE9 still rules, in many cases. I actually work all over this space, do not tell me otherwise. And now I have to maintain two codebases?

      • Roboprog 9 years ago

        Been there, done that. But you might mention to bosses/clients that MS no longer supports/patches anything older than IE-11 on desktop versions of Windows. They are most likely using an un-patch-able version of Explorer.

        Virii, Trojans and Hacks, oh my!

        https://www.microsoft.com/en-us/WindowsForBusiness/End-of-IE...

        • bigger_cheese 9 years ago

          My work "upgraded" to IE 11 late last year. The problem is so much of our internal infrastructure was built to target IE 8 (or earlier) that when our information services guys deployed IE 11 they forced it to run in compatibility mode.

          Now you have to go through this endless dance of Enable/Disable compatibility mode depending on what site you are trying to visit. We have a lot of non technical users so as soon as you ask them to delve into menu options to use some added functionality on a site you lose them.

          Even technical users hate this so most people sideload chrome. However a large number of workstation are locked down and those people have no option but to continue with IE.

        • spdustin 9 years ago

          Excellent advice that I give my students, and readers here will be well-served in following it.

          I don't even want to admit how many managers come back to them with "we mitigate that risk with user education, we have too many legacy (blah blah blah)." There's always some excuse, isn't there? Usually within departments, but once executive-level hears this sort of thing, they tend to at least investigate what the real risks are. So I'm adding on to your advice to other readers to suggest they "go higher" with their security warning.

          Man, I wish we lived in a world where management understood that people are shockingly good at finding ways of not doing what they're told!

      • extrapickles 9 years ago

        We use nw.js (customizable webkit browser) to provide an "application" for those customers that only have IE9 so we don't have to support IE9 in the web application. Sales pages still need to support IE9 though as they use IE9 to find the product.

      • intrasight 9 years ago

        My experience is that that ceased to be the case about a year ago. Now everyone also has Chrome.

        • spdustin 9 years ago

          Your experience isn't in healthcare, finance, military, manufacturing or oil and gas (to pop a few verticals off the top of my stack), it would seem. Literally 80% of my (adult, American-enterprise-employed) students in 2015-2016 so far have IE9 as their desktop standard, and have to beg for a special exemption to be allowed to install Chrome or Firefox.

          • epmatsw 9 years ago

            Even Epic has dropped IE9 support AFAIK. That's a pretty good indicator to me that healthcare has moved off it.

            • Roboprog 9 years ago

              Seconded. I am working on a project at UCD Med Center for California Dept of Public Health, which includes a pilot tie-in with Epic (even if it's just Epic shaking hands with our system and putting a short task's page in a frame).

              We started out in late spring / early summer back in 2015 saying we needed to support IE9, but that has since changed to 11. The notice from MS that nothing before 11 would be supported after January of this year (2016) forced the issue, I think.

              Back when I worked at a financial company two years ago we sure had mandatory crusty old versions of IE, though. Except for the groups that got special permission to use a browser that actually worked for things they had to have.

          • intrasight 9 years ago

            Besides military (haven't done that in 10+ years), I'm in all those other verticals and more. All desktops now have IE11 (because MSFT pretty much says "you must") and Chrome.

            • spdustin 9 years ago

              I wasn't speaking figuratively when I said literally, you know. :)

              It's a breath of fresh air when an enterprise student has a modern environment. But it's enough of an outlier (in my experience teaching all these different places) to still surprise me to hear when it's true.

          • moron4hire 9 years ago

            I've done those verticals, too. We always had Firefox. I don't know what it's like now. That was 10 years ago.

            (AKA sit down and shut up with your bullshit "sit down and shut up"s)

            • spdustin 9 years ago

              I literally deal with students in every class, a not-small percentage of students, that are disallowed by domain policy from installing another browser.

              • Roboprog 9 years ago

                I know :-(

                Give it a year. Without MS support, they will be forced to give up these older versions. Of course by then, IE 11 will seem quite "vintage", but that's life.

              • moron4hire 9 years ago

                I literally think you're an asshole for thinking you know everything about how enterprise works.

                IT can be brow beat just as hard as developers. They will change whatever domain policies you make them change. Quit being a pushover.

      • vinceguidry 9 years ago

        Your problem is actually simpler than if you had to maintain modern consumer-facing web apps, which have to deal with users across three broadly-defined screen sizes and a variety of mobile APIS. If you're serving the enterprise, then you can make assumptions about your audience that greatly simplify development.

        • spdustin 9 years ago

          Those assumptions are nowhere near as simple as you think when you are in a space that supports a large majority of all enterprise. You would shudder to see what real-world browser support is like when you write software to be used in that space.

    • netghost 9 years ago

      At the point when you write fallbacks for IE, you might as well just use an approach that works for all your supported browsers, otherwise you've got twice as much to verify and maintain.

      Check this out for an alternative to flexbox if you can't ignore that last n% of your users: https://kyusuf.com/post/almost-complete-guide-to-flexbox-wit...

      • freshyill 9 years ago

        With flexbox and a fallback, you're future-proofing. If you go with floats or something worse, you're working around yesterday's constraints.

  • kilian 9 years ago

    Flexbox is supported in all versions of IE that Microsoft themselves still support (IE 11 and up). You can still support it in IE10 too, albeit with a different syntax.

    That means even windows installations that haven't been updated since 2012 will support flexbox.

    • fizzbatter 9 years ago

      Unfortunately that still leaves out a ton of users. I know that's a tiny percentage, but tiny nonetheless. The shop i'm heading to soon has a small number of clients (<5k, each being very important), but with many using ancient systems. IE8/9 iirc. We use Table layouts for our "old compatible" product, and i don't think we'll ever move on from that. Some clients just refuse to update it seems.

      Luckily (for my sanity) we have a "new age" product that we can use responsive layouts for.

      • gotofritz 9 years ago

        Supporting old browsers should be treated as a special case though, like "people with js disabled" or something. Then of course you don't use flexbox (or serve different css fles or have a scaled down design or whatever). But the "norm" is that flexbox is now safe for most users.

      • gbog 9 years ago

        "Refuse to update" well yes, I would too, refuse to do something that is notoriously breaking a lot of working stuff for no known benefit. For example java applets developped for IE6 that is vital, because it drives the 10 years old exotic scanner, and nobody dares touching it.

    • hackerboos 9 years ago

      CanIUse reports bugs in IE11. Anyone had issues in day-to-day development?

    • NKCSS 9 years ago

      It's still common to find Citrix environments with IE 8/9 here in .nl healthhcare sector

  • guessmyname 9 years ago

    Last week I was in an interview with Amazon for a position in their web development team. One of the questions was related to this, they asked me to describe how to create the layout for a web page with two columns, I immediately thought about Flexbox but decided to describe the code using "float: (left|right)" and box-sizing, I felt that the two interviewers didn't like my answer because it is outdated.

    • asb 9 years ago

      Honestly that sounds like a case where you could improve your interview technique (or perhaps the interviewers could have done better on drilling down into your thinking). The fact you considered multiple options, evaluated them mentally and decided to describe the approach that would have highest compatibility is great, and explaining your thinking to the interviewers could have helped.

    • Brendinooo 9 years ago

      I can't find the source right now, but I've read that flexbox for page layout can still be problematic because a lot of times when you use flexbox it'll rely on the content inside of it to determine its flex width. So you'll get a bunch of page reflows while content is being loaded, which is less than ideal.

    • talmand 9 years ago

      I feel the interviewers didn't do their part in that exchange considering there are multiple valid ways of completing that task. As an interviewer I would have followed up with saying that method is not allowed for some made up reason, what's another way to do it?

  • MatekCopatek 9 years ago

    This largely depends on your target audience. Flexbox is only problematic for IE <= 9, which, according to caniuse.com accounts for less than 1% of all browsers.

    But this should always be checked against more relevant stats (your country, old website you're redesigning, etc.), so yeah, if you know you have a lot of people on IE9 and lower, flexbox is out of the question.

  • ggurgone 9 years ago

    There is a suit component for making flexible layouts in legacy browsers https://github.com/suitcss/components-arrange

    It is not as feature-rich as flexbox is but it works great - I built a similar one when I used to work at Yelp https://www.yelp.com/styleguide#section-arrange and it scales well.

  • bobbytherobot 9 years ago

    I've been using flexbox for the past 1.5 years. I'll add fallbacks, but it really is minimal if you are willing not to have it pixel perfect.

    Sometimes though I will use the fallback because it actually does it better than flexbox.

EdSharkey 9 years ago

Plug for test-driven CSS: https://github.com/jamesshore/quixote

I've experimented with it on a green field project and got promising results. Found I could refactor my CSS with confidence.

bbx 9 years ago

I agree with the Flexbox and DRY principles, but it's weird to still rely on arbitrary naming conventions like SUIT when CSS modules have been around for a while now.

Naming things has always been difficult, especially in CSS where it can lead to merging/overriding/precedence issues. Not having to think about what CSS class names are either available or possibly conflicting is a benefit from CSS modules that increases productivity by an order of magnitude I've rarely seen in CSS, especially in large codebases.

You've got a button and want to call it "button" and style it using ".button"? Go ahead. It will only inherit styles if you explicitly say so. The global namespace remains healthy for each component you write.

prashnts 9 years ago

Personally, I very much dislike using CSS classes unless required. I prefer having a clean markup with classes used only where they make sense.

For a context, I somehow can't wrap my head around writing something like:

    <div class="nav nav-inverse nav-hide-xs">
when `<nav>` makes more sense. Sure, if you have a case with alternate "inverse" navbar, go ahead with a class `<nav class="inverse">`.

About the flexbox, ah, well, even now they have undefined behaviour on several elements such as a `fieldset` [1].

[1]: http://stackoverflow.com/questions/28078681/why-cant-fieldse...

  • talmand 9 years ago

    These days using "nav" instead of <div class="nav"> is the preferred method by default. The other two classes are just modifiers that may or may not be required. There's nothing wrong with them.

    Also, I see "fixed" bug reports in both Chrome and Firefox when using flex with fieldset. To be fair, recent fixes.

Roboprog 9 years ago

FWIW, I'm using Angular (1.x) on a project at work, rather than React. One of the things I did recently was take the CSS file used in the project ("Few Pages App", rather than SPA, which had a common .css file), and turn it into an Angular (javascript) "directive".

I wish I had done this earlier. I have no "compile" step, it's just straight js plus the framework. However, I now have a mechanism to use variables for any (new) stuff with repeated settings, inserted into the rest of the text in the "<style> ... </style>" template.

kowdermeister 9 years ago

I've developed my last 5 projects (corporate websites with many different layouts) with SASS + Foundation 6 an no naming convention. Instead I relied on nesting selectors.

I can behave and usually not go deeper than 4-5 levels. It's a really neat way unambiguously tell a CSS rule where it should belong to. For example I can create a

    section.hero-block{ /* things inside are scoped */ }
CSS selectors who live outside are pretty basic, utility style ones, they exists on one level, so they can be easily overwritten by the scoped ones if needed.
  • Nadya 9 years ago

    This is how I've developed projects for the past two years. Every module is scoped. If it needs variations but contains the same HTML structure - it gets a modifying class (.full, .half, .side, .footer, whatever)

    If it has a different HTML structure - it is a different module entirely: `.module.v1` VS `.module.v2`

    Doesn't matter if 85% of the CSS is shared between v1 and v2. If the HTML structure is different, it is a different version of that module. If you can run a diff checker and return 100% the same HTML structure but you need a different coat of paint, you add a variation class. All modules begin as a "v1". This prevents it from needing to be added to the scope selector if a "v2" is ever added. I've yet to work at such a scale where the loss in CSS performance was a problem.

    Utility and State classes live in global space. Global being defined as anything unscoped, not "everything in CSS is global space". Since everything is scoped - I can safely reduce selectors. Very rarely does it go more than 3 levels.

    I use some level of OOCSS but don't use it for things like `.floatLeft`. If it is a style I will want to remove later, typically for responsiveness, then I don't want a class `.floatLeft` that is really `.floatNone` at a certain size. I would rather take `.item` and change `float: left` to `float: none` with a media query.

seag64 9 years ago

So, I don't do any front end work in my day-to-day, so this may be a stupid question. This article starts out with how CSS gets a lot of negativity. What alternatives are there? Do browsers understand anything but CSS for styling?

  • frankwiles 9 years ago

    There isn't an alternative really. Like Javascript, it's all there is.

    • seag64 9 years ago

      So are these other tools people are talking about some different methods that just transpile back to CSS in the end or something like that?

zephraph 9 years ago

I think an important thing to note here is that this individual's team is very small. If you have a small team that closely collaborates then scaling things which take discipline (like CSS) becomes vastly simpler.

CSS is difficult because it takes so much effort to do things the "right" way. It requires a good set of linting and testing tools or constant vigilance to maintain a correct, robust system.

As the codebase or team grows the difficulty of that task increases. That, to me, is why CSS often viewed in a negative light.

  • talmand 9 years ago

    I believe you could say the same for a large number of coding languages out there.

surganov 9 years ago

Recently I got into functional CSS:

https://github.com/chibicode/react-functional-css-protips

  • pluma 9 years ago

    At that point you might just go full css-in-js and embrace inline styles.

    I'm not sure which is worse:

    A) having twenty classes on each element, each doing only one or two things

    B) having twenty classes overlapping on the same one or two things

jorblumesea 9 years ago

Funny how all the original markup and languages are becoming the machine code of the web. No one writes js anymore, just compiles into js. No one writes css anymore, just SASS -> css. Html? Nope, directives or shadow dom.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection