Settings

Theme

CSS is powerful, you can do a lot of things without JS

github.com

493 points by NamPNQ 9 years ago · 318 comments

Reader

ctvo 9 years ago

I've worked with people who did things like this. It's not fun for anyone else on the team to try and figure out why you're using specific pseudo selectors on tags in a child inside a sibling in some label to make an accordion that would take 3 lines in Javascript.

  • gregmac 9 years ago

    I'd agree with the sentiment, but for a different reason. I think the method can be useful and maintainable, but, the problem with this implementation seems to be a mix of design (font colors, sizes) and functionality, and a lack of documentation.

    Splitting the CSS into two distinct pieces (or better: files, but I realize that's a limitation of jsfiddle) would go a very long way to making this technique maintainable. Having documentation that then shows the required HTML structure and the necessary classes to add would help immensely.

    Essentially, build it like a UI library that just happens to be written in CSS.

    Right now, it's just a demo of a technique that's not built in a reusable way, and you need to be pretty decent with CSS in order to understand and use it (since you pretty much have to re-implement it every time you want to use it). To be fair, the HN submission and site don't make any claims it's anything but this.

  • timdavila 9 years ago

    Using HTML5 tags such as <details>, you don't need CSS or JS!

    Try this in Chrome: https://jsfiddle.net/timdavila/f5rcarmn/

    • cstejerean 9 years ago

      Unfortunately this is not yet supported in any version of IE, including Edge.

    • irrational 9 years ago

      So I didn't try it in Chrome, and it doesn't work in Firefox, yet. But I can see where this is going and it would be awesome if it actually worked.

    • enraged_camel 9 years ago

      Whoa. I learn something new everyday...

    • rhgb 9 years ago

      It's defined in HTML 5.1, which is still Candidate Recommendation.

  • etjossem 9 years ago

    You never know when you're going to be stuck on a desert iframe with only CSS, and no access to JS...

  • ceejayoz 9 years ago

    I'm reminded of the Jurassic Park quote when I see people doing "neat" complicated CSS hacks to do stuff a line of JS would do...

    "Yeah, yeah, but your scientists were so preoccupied with whether or not they could that they didn't stop to think if they should."

  • adrusi 9 years ago

    Your complaint is essentially that they are using a language that other people working on the same project don't know. There are good reasons to discourage that: it fosters bikeshedding, and CSS's ways of expressing dynamic behavior doesn't match intuition as well as procedural javascript. However these reasons have to be weighed against technical limitations. Using CSS for dynamic behavior is often better than using javascript because many more people disable javascript than CSS. If the project requires javascript for some other important part of the page, then it's not worth the complexity of specifying dynamic behavior in CSS. But if all parts of the page work well without javascript, then introducing a dependency on javascript for something like an accordion is probably not rational if you have someone who knows how to achieve the same effect with CSS.

    • btdiehr 9 years ago

      Lets be honest, 99% of people who disable javascript are programmers who take great honor in complaining about every website that is more than 200k in size. This is a non-issue for most companies.

      • adrusi 9 years ago

        You're getting the wrong impression of those who disable javascript. Yes, they tend to be programmers, or otherwise tech-minded, because they have to know what javascript is, know how to disable it, and (most limitingly) understand the reasons for doing so. And naturally, if you disable javascript, you're going to be annoyed when sites don't work, going to consider the trend of requiring javascript regressive, and going to publically complain in the interest of promoting the health of your own profession. Notice that "taking great honor in complaining" is not the underlying cause of disabling javascript but rather an effect. The actual motivations vary.

      • jbverschoor 9 years ago

        I started disabling javascript since every site these days includes a gazillion badly crafted scripts that take up too much cpu. It actually brings my laptop to a grind

        (when having lots of tabs open)

        • erlehmann_ 9 years ago

          Anecdotal evidence: I have no problems having more than 200 tabs open on a Thinkpad T60 – as long as any JavaScript is disabled. Enabling JavaScript makes such a thing hard; there exist web pages that raise CPU temperature by more than 10°C.

      • Tanath 9 years ago

        If we're being honest, then no.

  • talmand 9 years ago

    I'm interested in seeing these 3 lines of Javascript that can implement an accordion.

    With a sane limit to number of characters on each line as well.

    • jonahx 9 years ago

      Here you go: http://jsbin.com/codedujeqe/edit?js,output

      JS:

          var panels = [...document.querySelectorAll(".accordion li")];
          panels.forEach(x => x.addEventListener('click', e => 
            panels.forEach(y => y.setAttribute('class', 
              y == e.target && !y.classList.contains('open') ? 'open' : ''))
          ));
      • epidemian 9 years ago

        Minor nitpick: if you're using classList, you might as well also use it to toggle the "open" class (instead of y.setAttribute('class', ...)):

          y.classList.toggle('open', y == e.target && !y.classList.contains('open'))
        
        As the behavior of what to do with the "open" class is only dependent on whether `y` is the clicked element, i find this version more readable:

          y == e.target ? y.classList.toggle('open') : y.classList.remove('open'))
        
        Aaaand, it can be made less readable again by selecting the classList method to call conditionally :)

          y.classList[y == e.target ? 'toggle' : 'remove']('open')
      • talmand 9 years ago

        Thank you, exactly what I was hoping to see instead of the usual arguments that don't actually fulfill the request.

    • Touche 9 years ago

      With jQuery it's probably like 4 or 5 lines. With plain JS a few more as you have to write your own iterator function.

      All an accordion does is add an event listener that removes a class from all elements and adds it back to one of them. Then there's a 1 line transition for that class in css.

      • talmand 9 years ago

        Is jQuery included in those 4 or 5 lines? One line of CSS in your accordion?

        • Touche 9 years ago

          If you had read the next sentence of my comments you would have seen that it would be a "few more lines" if you didn't use jQuery, basically you need a function like:

            function eachItem(arrayLike, cb) {
              return [].slice.call(arrayLike).forEach(cb);
            }
          
          So 3 more lines. If I said you can write a very verbose accordion in under 20 lines would that be good enough for you?
          • talmand 9 years ago

            >> So 3 more lines. If I said you can write a very verbose accordion in under 20 lines would that be good enough for you?

            Since that's more realistic, yes that would do nicely.

            • talmand 9 years ago

              Crap, can't edit.

              Two others completed the accordion in 3 lines task without jQuery.

        • justinlardinois 9 years ago

          I'm not sure why the actual jQuery library matters here. Chances are if you're using jQuery for an accordion you're also using it for a lot of other things.

    • nommm-nommm 9 years ago

      If one is already using jQuery - https://jsfiddle.net/jw75xznb/

      Yeah, it's incredibly crude but it is 3 lines and it took approximately 60 seconds.

      • talmand 9 years ago

        If it involves jQuery then it is not 3 lines. The original claim was 3 lines of Javascript. Making a claim something is only 3 lines of Javascript without including the fact that jQuery is required is a disservice to the many people that made jQuery the wonderful library that it is. That is the source of my disagreement.

        • nommm-nommm 9 years ago

          You're being disingenuous. Firstly, "3 lines of Javascript" wasn't meant to be taken literally. Not only that but 73% of the top 100,000 websites use jQuery - if you are on a large web development project you are more likely than not using jQuery.

          [1] http://trends.builtwith.com/javascript/jQuery

          • talmand 9 years ago

            Since two others have completed the task with literally "3 lines of Javascript" then I'm not being disingenuous at all. I requested the 3 lines was given roughly the same example by two different people.

            And I know the trends around jQuery, that was not the issue at all.

        • dwaltrip 9 years ago

          That isn't a disservice to jquery. The fact that people don't explicitly mention it could actually be viewed as a demonstration of its ubiquity.

          • talmand 9 years ago

            No, it's people becoming not being able to know the difference between jQuery and Javascript. Calling either of them the other is a disservice to both.

            • nommm-nommm 9 years ago

              I'm old. I wrote many, many, many lines of JavaScript before jQuery ever existed, I know the difference very well. Nobody is confused.

              Ignoring the fact that it clearly wasn't intended to be taken literally, "in 3 lines of JS" when speaking in the context of a team effort on a web application can be understood as "adding 3 additional lines to the source code." Context.

              There's no need to be nasty and argumentative for no reason.

        • enraged_camel 9 years ago

          >>If it involves jQuery then it is not 3 lines. The original claim was 3 lines of Javascript.

          jQuery is JavaScript, so...

          • adrusi 9 years ago

            Jquery is many lines of javascript.

          • talmand 9 years ago

            As pointed out, yes it is indeed Javascript. If you make use of it then you cannot claim your code is shorter in lines by choosing to not include the jQuery code.

            I've written a couple of small jQuery plugins and I don't claim I wrote this awesome Javascript code that does this cool thing. I say I made a jQuery plugin that does this cool thing.

    • gabemart 9 years ago
  • calsy 9 years ago

    I think the real question is why are you making an accordion? They are ghastly UI components to navigate for the end user. I could see a few limited cases for them, but if someone says 'we will implement an accordion layout' at work, im jumping all over that screaming NOOOOOO.

  • creshal 9 years ago

    Shouldn't pure CSS animations have better performance?

    • nevir 9 years ago

      CSS animations are generally on par with JavaScript, except when they're hardware accelerated.

      But that's changing once web animations (https://w3c.github.io/web-animations/) hits mainstream anyway - both CSS & JS get access to the same engine.

      • TD-Linux 9 years ago

        The point of CSS animations isn't HW accel - you get that just from layerization. What it does get you is animations executing off the JS thread, so if you have piles of third party JS it won't cause frame drops.

        • nevir 9 years ago

          Right, which you also get via the web animations API (queue up animations, and have them run on a separate thread)

        • at-fates-hands 9 years ago

          Good point.

          If you use Wordpress, like millions of people do, you will have a fuck ton of JS plugins running, so I can see where this would be advantageous.

    • awesomerobot 9 years ago

      If you have a sane amount of JS (ie, not loading entire libraries to accomplish an accordion) the performance differences should be negligible.

    • vkjv 9 years ago

      The animation, yes, but not the trigger. You can balance this by adding / removing classes in javascript (to limit the complexity in CSS) and with the class performing the animation.

  • draw_down 9 years ago

    I think the best way to deal with that is to use a CSS processor (I prefer Sass). You can make a "mixin" (or whatever term your processor prefers) that accepts a selector and styles it. Still readable, still no JS required (if you want to go that route), and you can document the heck out of it. "Oh no, more tooling". Yeah, more tooling.

  • orthoganol 9 years ago

    Sounds odd, your teammates are hardcoding extremely common page components from scratch, i.e. at least not an internal library/ module where you only write it once? That seems like the bigger problem you have.

    If you only write it once and put it somewhere, among other advantages, you can document it easily.

    • macandcheese 9 years ago

      You still need to write the initial block of code. Advocating for non-custom elements just because it already exists in Bootstrap or Foundation is an easy way out, especially for UI uses. It doesn't matter how an element was created as long as it's re-useable - there's nothing stopping you from handcrafting your own UI elements and re-using that block in your design system...

  • kelukelugames 9 years ago

    Do you know of a Github repo that implements these features in javascript? I would love to learn how.

    • ceejayoz 9 years ago

      Most of these (carousel, tool tips, modals, etc.) are in the very popular Bootstrap.

achairapart 9 years ago

Most of these are just clever CSS hacks. There is a website collecting these kind of experiments since the early '00: http://www.cssplay.co.uk/

There was a time when separation of concerns and the "Rule of Least Power"[0] where the foundation principles of web development.

Today you have preprocessors, postprocessors, transpilers, content and style in JavaScript, behavior in CSS. Very powerful tools that can easily lead to unnecessary complexity.

On the other hand, somehow W3C failed to turn these principles into a truly interoperable and semantic web.

Ah! Also, nobody cares about unobtrusive JavaScript anymore.

[0]: https://www.w3.org/2001/tag/doc/leastPower.html

  • cptskippy 9 years ago

    > Ah! Also, nobody cares about unobtrusive JavaScript anymore.

    I do. I also care about graceful degradation. There are certain times (e.g. Web Apps like Gmail) where graceful degradation is almost impossible and unobtrusive JavaScript would be silly but those are the exception. Most sites on the web are just content and there's no reason to have excessive JavaScript or any reason why the page can't be perfectly functional without it.

    • jhall1468 9 years ago

      Just because something can be done a certain way doesn't mean it should be done a certain way. Minimizing javascript for the sake of minimizing it is silly.

      People that disable javascript represent a tiny percentage of the population. No one is going to make engineering decisions based on that tiny percentage, anymore than people still target IE6.

      • cptskippy 9 years ago

        I'm not talking about minimizing for the sake of minimizing. I'm talking about not using JavaScript for the sake of JavaScript. Or better, not using JavaScript because you can't be bothered to understand what your problem is or how to avoid it.

        - Page content doesn't need to be side-loaded in AJAX.

        - Site layouts don't need to be set in JavaScript at page load. Animated menus don't need to be done in JavaScript and neither do pinned toolbars, doing so usually causes issues and stuttering when scrolling because you have a script running every pixel shift.

        - Every link on the page doesn't need to be a JavaScript function, it makes bookmarking or opening in a new window difficult to impossible to what benefit?

        - If you do want something to open in a new window, you also do not need JavaScript.

        - User controls don't need to be JavaScript and when they are, they usually fail to work in mobile.

        - Popover slideshow galleries don't need JavaScript to manage page reflow. Most shopping sites do this for their product images and it completely falls apart on Mobile when you pinch-zoom.

        Far to often I find myself on pages that are unresponsive (not referring to Responsive Design) because they're so laden with JavaScript that everything comes to a screeching halt. Or worse still, some syntax error in one script brings the whole page down or one script reference doesn't load and the page is completely unusable.

      • ForHackernews 9 years ago

        Yeah, who cares about people using screen readers! Or search engines...

        • depr 9 years ago

          Google executes Javascript, and

          >It is a common misconception that people with disabilities don't have or 'do' JavaScript, and thus, that it's acceptable to have inaccessible scripted interfaces, so long as it is accessible with JavaScript disabled. A 2012 survey by WebAIM of screen reader users found that 98.6% of respondents had JavaScript enabled.

          http://webaim.org/techniques/javascript/

    • the_gastropod 9 years ago

      I often hear rationalizations about how x couldn't be built with graceful degradation in mind. There certainly are _some_ examples (games, for example). But GMail doesn't strike me as a particularly compelling example. GMail is also _just content_. The fancy ajax interactions, though nice, are hardly required for an email client.

      • sanderjd 9 years ago

        This is a-historical by my memory - the entire reason Gmail became so successful was that its use of "fancy ajax interactions" made it shockingly nicer to use than any of its competitors at the time.

        I think if one of your main selling points is interactivity afforded by javascript, then it is unlikely to have much return on investment to accommodate users who don't want that. But for sure people should be thinking harder about what their selling points really are - the market for "it's better because of ajax!" is probably tapped out.

        • FroshKiller 9 years ago

          AJAX isn't why Gmail became successful. What set Gmail apart from its competitors was the huge amount of initial storage you got (1 GB for free at a time when Hotmail offered less than 10 MB for free), a higher maximum attachment size (25 MB compared to the webmail standard 10 MB), Google search, and conversation view. All of which, by the way, worked with the AJAX-free basic HTML view.

          • sanderjd 9 years ago

            Well, I doubt either of us have statistics for what really drove its success (and if you do, I'll gladly cede the point), but anecdotally, I and a lot of my friends at the time switched to Gmail not because we needed more storage (I don't remember even thinking about that as a problem with Hotmail at all) but because the interface was way better. If anything, I think it had more to do with the "cool" factor of getting an invite and the cachet of Google at the time than with the storage. But I freely admit this just personal experience talking.

          • CaptSpify 9 years ago

            Also the spam filtering was years ahead of it's time

          • qu4z-2 9 years ago

            I had forgotten how big a change conversation view was compared to other webmail.

            Also for what it's worth, I still use the Basic HTML view because I find it a better experience, so AJAX was definitely not the selling point for me. The 1GB thing was a huge factor though.

            • cptskippy 9 years ago

              For me, the basic view has always felt neglected and kind of halfassed. The full experience has fully styled UI elements where as the basic view just defaults to the browser defaults. Outlook does this too.

              To me it just feels like basic view is just v1.0 from 2004.

              • qu4z-2 9 years ago

                It's definitely the uglier of the two views, no question. I prefer it functionality-wise though. It does less of its own window management, etc.

      • afarrell 9 years ago

        I think doing what they do, having a less-fancy separate client, is less complex.

  • adrusi 9 years ago

    The semantic web failed in large part because browsers didn't implement XSL, and so the average web developer never learned about the idea of sending structured data to the client as XML and using XSLT to instruct browsers to render the data as XHTML. If these specs hadn't been released in the middle of Internet-Explorer-monopoly-induced-browser-stagnation then they wouldn't have been dismissed as failures by the time browser competition increased and standards started to be honored.

    I'm not sure that the semantic web would succeed even if it were a new idea today. HTML5 was popular because it gave web developers tons of shiny toys and got them excited to use it. XHTML was conceptually beautiful but it hardly enabled any user-visible improvements over HTML4, so only the philosophically-minded web developers gave a fuck.

  • harryf 9 years ago

    Hmmm...

        .accordion .content {
            padding:0 10px;
            overflow:hidden;
            border:1px solid #fff;
            -webkit-transition: all .5s ease-out;
            -moz-transition: all .5s ease-out;
        }
    
    -webkit-transition, -moz-transition... it's like we're at 180 degrees to where the web was in the days of IE4-6
    • clarry 9 years ago

      Remember when Good Developers would hate on framesets because they break the back button and linking and everything?

      Now it's totally OK to break all that with AJAX and "text-as-apps"... I much prefer the days of the old web.

      • nkassis 9 years ago

        Days of the old web where flash was pervasive and best viewed in [IE6|Netscape|Mosaic|...] pages were everywhere. Every generation of the web has had really crappy devs building bad experiences. The current generation is not making anything worse than it's predecessor.

        • inanutshellus 9 years ago

          My current-favorite problem with modern web development is mobile-specific redirection.

          e.g. you click a link in your email and it takes you to "www.foo.com/somethingWithParametersAndImportantStuff", foo.com detects you're on a phone and redirects you to their mobile homepage at "m.foo.com", blowing away your URL or even better not supporting your particular URL's page in the mobile site... where... your mobile browser could've just rendered the original site, albeit pinched.

          It comes to mind because I'm currently dealing with this as an issue with UPS.com. We're halfway to 2017, people! How can we be having these problems.... :-)

          • jdmichal 9 years ago

            http://xkcd.com/869/

            Anyone know where I can find publication dates for individual comics? I don't see anything on the comic's page.

          • JoeAltmaier 9 years ago

            Digression: 'clicking on a link' may become an obscure reference soon, like dialing a phone. How many young people ever use a mouse?

            • sanderjd 9 years ago

              I'm very curious about this: is there a hypothesis that non-mobile computers are going away in the business world and/or that "young people" will not be involved in that world? I don't know the stats - are tablets making big inroads in business computing?

              • WorldMaker 9 years ago

                Humans have several millennia of evolution "touching things" for tactile feedback. Mice on the other hand are a relative (and quite useful) hack compared to that. It requires training and a different mental dimensional model to use. To a child growing up with modern touch screens, a screen without touch is the aberration and "broken". Mice may not disappear entirely, but certainly more and more screens in our lives will support touch interactions, even on desktops and "non-mobile computers", simply because it requires less training and feels more natural ("touch the button" versus "move the mouse to the button and click" may not seem that different after decades of mouse usage, but are very different experiences to an untrained person). There's a sense already today that kids growing up with tablets find mice strange and annoying ("Why can't I just touch that?"), and it's easy to wonder watching today's kids if mice will last for more than a footnote in history and in increasingly small niches that require "headshot precision" like games and maybe CAD.

              • JoeAltmaier 9 years ago

                Dunno. But my niece and nephew are tablet/phone experts, and have never used a mouse. And they are 4 and 6.

                • MichaelBurge 9 years ago

                  If it comforts you, I used an upside-down SNES gamepad for a few years before ever touching a mouse. And today I use my mouse far more than any game controllers.

                  • mitchty 9 years ago

                    I'm more curious why it was upside down.

                    • MichaelBurge 9 years ago

                      I just grabbed one and starting using it upside-down. By the time anyone told me it was wrong, it already felt more natural to use it that way.

                • clarry 9 years ago

                  I think that just means new computing devices have expanded the market, not replaced old devices. Some functionality that was once used exclusively on PCs (what else did you have?) may now be more commonly accessed via mobile devices. You didn't have a PC in your pocket when you needed to look up directions on a map..

            • ZanyProgrammer 9 years ago

              Any young person ( please define) who has ever used a desktop computer?

        • clarry 9 years ago

          Well, "your browser is unsupported" is something I still live with. And on the other hand, if I don't have the setup the developer expects, things just quietly break with nothing to tell me what's up. How is that better?

          Flash never really was a problem for me; very very few used it for anything critical. It was mostly for entertainment and media that has no value for me. I lived just fine with no flash installed, and got performance & security benefits for simply not having it. Living with JS (and other obnoxious features) disabled, on the other hand, has gotten really fucking difficult now.

          And frankly the "best viewed in whatever" websites weren't a problem either. On one hand it was mostly fanboyism. On the other, web designers using some niche feature that had no real impact on functionality or my ability to read & navigate the content. Again, I don't recall ever having to switch to another browser because of that. So it really was better for me back in the day.

          • nkassis 9 years ago

            "Flash never really was a problem for me; very very few used it for anything critical."

            Actually there was a period (end of the 90s, early 2000s) where flash was pervasively used to build entire sites. They were worse than single pages app of today. Completely broke browser history, urls etc... Those are similar complaints to today but now that APIs and workaround exit, it's mostly laziness that prevent people from properly building apps that avoid these pitfalls.

            "And frankly the "best viewed in whatever" websites weren't a problem either".

            There were days where not having a windows machine with IE installed meant not being able to bank online, access university course website etc... This is no longer an issue that I run into much in 2016.

            "Living with JS (and other obnoxious features) disabled, on the other hand, has gotten really fucking difficult now."

            That used to be the case too with Flash (and java to a smaller extent). Without flash many many sites were completely broken. This obviously got better with time to the point where it's hard to remember but it was pretty horrible to try to use the web without flash circa 2000-2006 or so.

            I get that some want JS disabled but it's the only cross browser method of achieving certain interactive experiences on the web. It's not new technology and has been around since the earliest days of the web. The percentage of people with JS disabled is so low (less than 1% in sites on many sites I've dealt with) that it was very hard to justify the added effort to support both (in the case of the sites I worked on, they were large enough that the effort was made). As the web becomes used for more and more use cases, it's going to be hard to keep accommodating a very small minority of users. If JS wasn't there, something else would have to exist to do what it does.

        • TorKlingberg 9 years ago

          "best viewed in Chrome" is getting annoyingly common.

          • inanutshellus 9 years ago

            Bank Of America recently told me it only supported Safari and Chrome on MacOS... But... supported Firefox on Windows. Whaaaa....

            • jdmichal 9 years ago

              "Support" means they are on the hook if something is broken. Every OS/browser combination is a cost center and potential liability.

            • clarry 9 years ago

              And my bank keeps constantly nagging me that my browser (Firefox LTS) is no longer supported and that I must update immediately.

            • nommm-nommm 9 years ago

              I called my bank because I couldn't log in

              "We recommend Internet Explorer."

        • JustSomeNobody 9 years ago

          >... is not making anything worse...

          That's a pretty low bar.

          • jdmichal 9 years ago

            Maybe, but it's an accurate assessment to someone pining for the "old days"...

        • otabdeveloper1 9 years ago

          > ...and best viewed in [IE6|Netscape|Mosaic|...] pages were everywhere

          We have "best viewed in Chrome" today, which is no different.

          • nkassis 9 years ago

            nope I agree, like I said it's as bad as it ever was. The past wasn't better.

      • oliwarner 9 years ago

        I would strongly disagree with "totally OK".

        A crappy, lazy developer won't care about state history. A good developer will. You can do things right if you want to. It's more work but not a huge amount more.

      • SquareWheel 9 years ago
      • Hamcha 9 years ago

        I have to maintain a web interface with framesets and it's much worse than the React stuff I build. Yes it's "one huge js-dependant page for everything", but it can keep track or where it is (and go back to it) using location.hash or path entirely (if the webserver agrees). So I can fix single page apps, I can't fix framesets.

        • clarry 9 years ago

          From a user's perspective, what you [as a developer] can or cannot fix doesn't really matter. What's broken is what matters. I find that with the JS craze we've been living for a few years now, things break a lot in the same way they did back in the frameset days. Except that now it is worse in some ways; with framesets, I could link to a specific frame if I wanted. And I could navigate back and forth too, as long as I understood the mechanics behind it. Now with the JS crapps, it's no longer something I can work around as a user.

          • sanderjd 9 years ago

            > JS crapps

            Just as a pointer, using this "portmanteau as diss" discourse style is generally a bad idea if you want to be persuasive to people who aren't sure yet whether or not they agree with you, rather than just "preaching to the choir" who already share your views. The rest of your comment made some decent points, but name-calling like this just comes off as childish.

      • ceejayoz 9 years ago

        Every modern framework I'm aware of has either built-in or popular third-party routers that use HTML5's History API to make the back button and links work just like they'd work in a static HTML-only site.

    • iamtyce 9 years ago

      Autoprefixer and prefixfree allow for writing 1x declaration and as support improves over time the prefixes are automatically dropped from your build.

    • nostrademons 9 years ago

      The browser prefixes haven't been necessary on transition for almost 3 years now:

      http://caniuse.com/#search=css%20transition

      This is just a webdev with old habits that isn't staying current.

    • ricardobeat 9 years ago

      transition has been standardized and available in all browsers for years already, that is only necessary as fallback for very old browsers.

      • talmand 9 years ago

        The only reason I use the webkit prefix on transition is for Android, otherwise I would say it isn't necessary at all.

        • ry_ry 9 years ago

          Still a suprising number of old safari builds out in the wild, from a very quick look at our GA. Largely elderly iphones I assume?

          Either way, I'm reticent to pull the WebKit prefixes from our mixins for now.

          I wonder if my employers would be interested in releasing (& aggregating with other relatively large sites) our browser usage stats to create a categorised set of current 'real world' stats?

    • zeveb 9 years ago

      I think we learned from X- headers and x- media types that vendor prefixes are a mistake: inevitably one must support vendor-prefixed keys forever. That's why that practice is no longer recommended: just use the right key, and specify it properly so others may support it as well.

  • toomanythings3 9 years ago

    The W3C's job is to standardize implementations. Most standards bodies do not invent on their own. In any case, a standards body will generate the fundamentals allowing the ability to piece together components to create what a developer wants. No standards body is able to come up with every desire of every developer.

    • achairapart 9 years ago

      The point is: Usually, you must know the rules to break them. In this particular context, looks like the original rules are fading away.

      No rules = Anarchy.

      • nilved 9 years ago

        Nitpick, but anarchism is not the lack of rules, it's the lack of rulers.

        • Piskvorrr 9 years ago

          That's not really a nitpick: in case of the Internet, it's the main modus operandi - with various warlords carving out a temporary fiefdom here and there (remember the Browser Wars, when IE had 90%? Brace yourselves, we're headed for a re-run with Chrome), but no actual rulers or enforcement.

        • achairapart 9 years ago

          My bad, thanks for pointing it out.

danielnixon 9 years ago

Numerous accessibility issues here. Many of these examples can't be operated by a keyboard, for example. "CSS only" is not a virtue if it comes at the cost (as it always does) of needlessly excluding people from the web.

  • grahamel 9 years ago

    Was about to write the same. The three examples I clicked on - tabs, accordion, and menu - didn't work via keyboard.

    All of these are fairly simple show and hide interactions that are easier to use, build and maintain when done with javascript, with all the content shown if JS is turned off, not fully loaded or broken.

    • extra88 9 years ago

      The accordion can work via keyboard with some styling changes, e.g. position or clip checkbox instead of display:none, add visual indication on :focus. I didn't check the others but their accessibility may be similarly correctible.

      Of course for accordion in particular it would be better if the pure HTML solution of using <details> and <summary> elements was supported in all browsers. They're already in Chrome and Safari and will come out from behind a flag in the next Firefox version. A polyfill for IE etc. can bridge the gap.

      • grahamel 9 years ago

        True, yet when examples like these are added without basic keyboard accessibility in mind they can get added to projects in the same half finished state.

        How many sites using Meyer's reset didn't add focus styles to links? Even with the comment /* remember to define focus styles! */

        It's not the fault of the original developer but it certainly helps to have more robust examples.

      • danielnixon 9 years ago

        As one counter example: you'll never make a modal popup accessible without JavaScript. The focus management required is impossible with "CSS only".

  • CaptSpify 9 years ago

    It's funny to hear this argument. I constantly hear "well, we don't worry about non-js browsers, because they are such a small minority". Yet how many people are keyboard-only users?

    I'm not saying your wrong, or that you are arguing against non-js browsers, just a funny twist.

mcv 9 years ago

I prefer using CSS for my styling and javascript for my functionality, as God intended. These examples could be educational for getting a bit more out of your CSS while keeping only the pure functionality in javascript. Too much styling-related stuff seems to be sneaking into code these days. I like my concerns separated.

  • clifanatic 9 years ago

    > I prefer using CSS for my styling and javascript for my functionality

    To play devil's advocate, though... is an accordion or a carousel "functionality" any more than, say, a drop-down or a multi-line input box is? I mean, the games examples are pretty wacky (in a cool but "thank God I don't have to debug these" way), but things like tabs and tree views are so ubiquitous that a case could be made for having standard HTML input tags for them.

    • mcv 9 years ago

      They just display stuff, right? I'm fine with having those in pure CSS if it can be done in an understandable and maintainable way. But the decision to display a message in a modal popup when you click a button is functionality and should be javascript. The behaviour of the modal popup itself is fine as CSS.

      Well, that's my opinion at least.

    • timdavila 9 years ago

      > a case could be made for having standard HTML input tags for them.

      and for the accordion at least, the case was made and approved. check out <details> and <summary>

code_research 9 years ago

I am missing one important argument in this discussion:

CSS only design is an important piece of a future web with reduced security and privacy threads.

The (interesting) model of allowing remote code execution per default was a beautiful, but naive vision. We have to make big advances in technology, politics and society to make this model work in a way that does not make internet users victims by default. We are not there yet. Reality is: the crooks destroyed that vision and are advantaged by the current situation, while all internet users are being trapped in their first moment of browser usage without their consent or knowledge.

For many use cases, (e.g. government websites, banking, anything where you type in your name) css-only design should become a requirement by law to protect the user until we figured out how to write secure software that respects user privacy and how to form governments that will respect their citizens (possibly will take longer). Until then browser vendors should implement more and better possibilities for CSS that help to avoid JavaScript whenever possible.

I very much like JS animations and stuff happening in the browser window, also there are some edge cases where JS brings some important advancements to a UI, but we have to face that privacy and security are much more important issues than having a nice UI and we have to change the current situation, as we, as programmers, are responsible for it.

The "remote-execution-by-default" experiment has failed, we need to change that, and CSS is a great way to go on with a web that might be less problematic for everyone, but still offers very nice usage experiences.

  • vroombaprime 9 years ago

    Browsers/webapps have only become this crazily successful because they allow seamless delivery of applications to run locally. I haven't seen anything to build "code-less" apps that can implement the complex features people want and isn't a complete nightmare to build and maintain. Until then everything you're talking about is just a pipe dream.

    You can still make the apps you're talking about with html+css and enforce js=off in your user browsers, but there is a reason no one wants to do that these days.

    And unless I'm not mistaken, there have been plenty of exploitable bugs in the core rendering engines that involve only html/css, so your utopian world STILL depends on a secure sandbox.

    • CaptSpify 9 years ago

      > Browsers/webapps have only become this crazily successful because they allow seamless delivery of applications to run locally.

      I'm going to heavily disagree with you. There were plenty of sites that were successful without using heavy JS. Most webapps I see can run easily without JS, they just choose not to. Yes, there are exceptions, but they are exceptions.

      "The core features people want" aren't JS-pop-ups, and slow browsers. They want sites that work quickly, are easy to understand, and work on mobile just as well as on a desktop. I would argue that JS makes all of those aspects worse.

      • sanderjd 9 years ago

        > They want sites that work quickly, are easy to understand, and work on mobile just as well as on a desktop.

        Not quite: users want to achieve specific tasks as quickly and easily as possible. Certainly "work quickly" and "work on mobile" are two huge pillars of that for many (probably the majority of) tasks, but for many applications you have to make significant trade-offs in functionality under the constraints of a static site.

        Anything built on the web is competing with something that already is or can be built natively. Native applications don't have to concern themselves with this sort of limitation on interactivity as a trade-off for latency, which is an advantage. On the other hand, the web has the (huge) advantages of open discoverability and no-install distribution. It makes sense for both platforms to be working to fill in their gaps while trying to minimize the trade-offs.

        It's clear that slow startup due to big chunks of js (and media) on load has become a big problem, and people are working on that, perhaps without much to show for it yet, but it isn't obvious to me that ceding the territory of interactive applications back to native implementations would be the better way forward.

        • CaptSpify 9 years ago

          And it's not clear to me that fixing a broken system is worth the time, when we have a working system standing by idly. I don't know of anyone who is asking for more interactiveness for most of the web, but I do know that non-js works, and works well. It may not be as "interactive", but I view that as a good thing.

          Of course, this is all in context of a typical webpage. There are exceptions to this.

          • SquareWheel 9 years ago

            > I don't know of anyone who is asking for more interactiveness for most of the web

            Hi, that's me. The reason is, quite simply, because this is not a good user experience:

            https://pbs.twimg.com/media/CmaP3JvUcAA8-5a.jpg:large

            The open web is my platform of choice, and the technology is finally there. Progressive Web Apps[1] offer the features of native but are instantly-available, without downloading or installing. So yes, I very much want that as a developer.

            https://developers.google.com/web/progressive-web-apps/

            • CaptSpify 9 years ago

              I don't see how that image proves your point. Shitty designs are shitty if they are in a web-app, or mobile-app.

              OK, fine. I'll concede devs want more interactiveness. I have yet to see evidence that users want more interactiveness. I think that points to the arrogance of devs "who totally know better than the user".

              • SquareWheel 9 years ago

                Users want positive experiences, and devs want to build those positive experiences. Look at some of the most popular websites out there: Youtube, Spotify, Amazon, Reddit - they're built on interaction. You're not just reading a post on reddit, you're upvoting it and influencing the front page.

                This had traditionally happened through POST/GET requests and having all the logic server-side. Yes it's possible to build interaction without Javascript, but it's not a great effect. Imagine if you had to wait for a page load every time you voted on a post on reddit.

                Now extend that to modern webapps. Take Google's Voice Memos demo[1]. It loads instantly. It supports any device. You can even add it to your homescreen and you won't be able to tell it from a native app. Everything about it just works. Why would a user not want such an experience?

                Javascript interaction is the natural evolution of the web. If it wasn't JS it would have been something else. This growth has been driven by users, devs, and browser vendors alike. There's nothing "arrogant" about it.

                [1] https://voice-memos.appspot.com/

              • sanderjd 9 years ago

                That's funny, I just replied to you arguing the opposite. People in tech are the only ones I ever hear complaining about rich web apps. YMMV I suppose!

          • sanderjd 9 years ago

            > I don't know of anyone who is asking for more interactiveness for most of the web

            I don't know of anyone, besides programmers, who doesn't like the current interactive-web-app web more than the decade-ago full-page-load web. They don't like ads and popups and things being slow either, but they love Gmail and AirBnB and Facebook and on and on. We should solve the problems without throwing away all the good stuff.

    • code_research 9 years ago

      > but there is a reason no one wants to do that these days

      The reason is, that JS is enabled by default, nothing else.

      If users had the possibility to actively decide before any remote code will execute on their computer, how many would like to enable it?

      We are just one default checkbox setting away from what you call "utopia" here - a word that should be used for much bigger things.

      Of utopic naivity in deed is the expectation that such powerful features will not be misused - delivering browsers with code execution enabled by default will be looked at as one of the most funny things of the first internet in a few decades.

      Web application development paradigms that enforce JavaScript usage as an absolute necessity are examples of "naive utopian deadends". It is totally anti-avantgarde and anti-progressive, we should not waste so many young talents on that.

      • vroombaprime 9 years ago

        I'll be the first to lament the spread of javascript, SPAs, and the huge hit to accessibility that the web has taken over the years.

        None of that changes that js adds incredible power to what webpages can do and there is zero chance of rolling back browser-delivered applications at this point.

        I also don't understand why you think html+css doesn't have the same fundamental 'code execution' flaw - you're accepting unseen input from a remote source and feeding it into an execution engine which will have exploits - whether that's css or html or js or xml or *.

        Back to your question though: yes, 98% of web users want remote code execution on because they want spotify, facebook, and youtube to work. They would be upset if they even had to manually go in and enable it. And I'm not even sure you could make a quality version of those sites without js.

  • achairapart 9 years ago

    What do you exactly mean with "remote-execution-by-default"? As far as I know, all browsers have strict "same-origin" policies by default.

    • e12e 9 years ago

      Apart from other points sibling comments have made - the current Web is very much a mush of "trust one site" leads to running code from three, four different domains via CORS and whatnot. My favorite alerts in noscript are people running js from bare cloudfare and s3 domains (do you trust all js publicly available on s3?) (and other cdns) - and also the "secure" amazon stuff like the hn search-box: some random AWS/cloudfront subdomains, a third-party service (algolia) and its accompanying domain for static resources.

      It might be convenient and powerful - but secure? With our current huge (in code and complexity) browsers? With the series of bugs in font rendering, image libraries etc?

      [ed: autocorrect. Apologies for seemingly calling algolia "third-rate" for a while there!]

    • code_research 9 years ago

      "remote-execution-by-default": web browsers execute code that was loaded from an untrusted source somewhere on the internet. Every (ok, most) browsers by default allow any website you visit to execute JavaScript code in your browser.

      "same origin" is about the source of that code, only of minor relevance here as long as no working signed code distribution mechanism and infrastructure exists - why not, btw, after all these years?

      For communications and general information transmission we do not need remote code execution.

      Yes, browsers try to do that in a "safe way" - the "sandboxing" approach has been exercised for many years now, mostly without success. Maybe Qubes OS can be a successful approach to this problem, but we still have too many non-technical problems to solve, as reality shows, so enough time to do more research. Until then: css only should be the default.

      CSS gives us a very good way to stop going on with that inacceptable defaults while we fix the first version of the internet.

    • wtbob 9 years ago

      > What do you exactly mean with "remote-execution-by-default"? As far as I know, all browsers have strict "same-origin" policies by default.

      Even with the same-origin policy, the default behaviour of a web browser is to execute code it downloads from a remote site (i.e., remote to your computer); as it turns out, this is an utter disaster for security and privacy, turning what is a relatively securable platform (HTML+CSS) into a nightmare.

      It is not, today, possible to be secure and private while allowing JavaScript. That's a problem.

adamjc 9 years ago

The problem with relying on anchors means it stays in the browser history, so if you press 'back', you get the modal dialog again!

I don't think this is very useful, but it is a fun exercise in CSS.

nnq 9 years ago

May the gods have mercy on the soul of who'll maintain code using these... "techniques".

(I know because back in the days I've written things like this myself :) ..probably the curses whispered by those who've had to endure their progenitors are finally getting at me)

zaidf 9 years ago

History is going to look back at CSS in disbelief when it calculates the amount of engineering time was spent trying to position elements correctly.

This isn't hating on CSS as much as how broken layout creation is with no end in sight--but plenty of hacks.

  • iLoch 9 years ago

    CSS layout is actually pretty good these days, with flexbox anyway. It's hard to come up with a better layout system used anywhere near as much as CSS.

    • mungoid 9 years ago

      Agreed, however there are a ton of companies with extremely outdated os/browser policies, that refuse to update for whatever reason. Been a contract developer for ~10 years and even this year we were told to support IE 8 on a specific project because some fortune 50 company needs us to (Seriously). There were plenty of modern tools that helped reduce issues but there was still a bit of headache.

      • reitoei 9 years ago

        That headache is what you get paid for.

        • Piskvorrr 9 years ago

          Nope. There's usually plenty of work to do; supporting IE4 (or FF 3, or whatever Webkit shipped on Android 1.6) just makes it longer and over the budget, while squeezing out other projects.

          In a word: busywork.

  • talmand 9 years ago

    What do you mean? It's quite easy to position elements on the page however you please. It can get quite complicated if you wish to support multiple viewport sizes with dynamic resizing, but it can be done.

zuxfer 9 years ago

And here I am, trying for past 10 years to centre align a div, both horizontally and vertically.

jordanwallwork 9 years ago

The problem with using css this way is that it's not as obvious what's supposed to happen as it is when using js. I'd love for there to be some explanation within the examples of _why_ they work - I've just been reading the first modal example but I can't really understand it

  • nurettin 9 years ago

    Building web applications with screens that have complex workflows and state is a need that is largely ignored by browsers and web standards.

    Instead of getting reusable gui components we get indechiperable css hacks that were built for creating art installations on the web rather than getting any actual work done.

    • digi_owl 9 years ago

      Using what was supposed to be a document display format for developing application interfaces is a massive hack in the first place...

      • nurettin 9 years ago

        And using style sheets that were initially for styling documents for animation/graphics, and using javascript which was created as a lightweight language for non-professionals to create reactive diff-based dom manipulations, and...

    • icebraining 9 years ago

      Mozilla (including Firefox) had XUL, but nobody cared.

      • wtbob 9 years ago

        > Mozilla (including Firefox) had XUL, but nobody cared.

        Have you seen XUL? Here's an example, from https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Tu...

            <?xml version="1.0"?>
            <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
            <window id="findfile-window"
                    title="Find Files"
                    orient="horizontal"
                    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
            
              <button id="find-button" label="Find"/>
              <button id="cancel-button" label="Cancel"/>
            
            </window>
        
        All that does is display a window with two buttons. You can imagine how hideous it could get when it got more complex. Now, imagine this alternative (I'm assuming that id & title are mandatory arguments, and that orient is optional, default to horizontal):

            (sul
             (stylesheet "chrome://global/skin" "text/css")
             (window "findfile-window" "Find Files"
                     (button "find-button" "Find")
                     (button "cancel-button" "Cancel")))
        
        Which would you rather write in?

        Now, imagine that JavaScript were Scheme or Lisp instead, so that your browser interaction code were also written in an s-expression language. And imagine that CSS were s-expression-based, so that you were using the same tools to manipulate the same data everywhere.

        It makes me weep.

        • talmand 9 years ago

          I must be insane because I don't really see that much of a difference between the two examples you provided. I can read one just as well as the other.

          • wtbob 9 years ago

            The former has 46 words/348 characters; the latter 20 words/176 characters. That's more than twice the tokens, twice the disk space, twice the cognitive load.

            • icebraining 9 years ago

              Frankly, it's silly to think that cognitive load is directly proportional to number of words/characters.

              For example, the latter relies on more implicit information (the order of the arguments), which can be harder to keep in mind than the keywords use by the former, particularly as you add more than two attributes. I'd say this version actually reduces the cognitive load, but it doesn't save as many words:

                  (sul
                   (stylesheet :href "chrome://global/skin" :type "text/css")
                   (window :id "findfile-window" :title "Find Files"
                           (button :id "find-button" :label "Find")
                           (button :id "cancel-button" :label "Cancel")))
            • talmand 9 years ago

              Twice the tokens, don't care.

              Twice the disk space, who cares?

              Twice the cognitive load, I guess I have a high tolerance.

              Still don't see a compelling reason one is better than the other.

      • izym 9 years ago

        Was it ever meant for general web usage?

        • icebraining 9 years ago

          For a time that was talked about (and Firefox supported XUL-based sites up to version 4).

  • steventhedev 9 years ago

    The :target pseudoclass is used, along with anchors. It means that it also pollutes the browser history, which is somewhat appropriate for modals, but probably not what you want.

    Still neat though.

    • jordanwallwork 9 years ago

      How does the browser know which modal is targetted though? I thought :target had to match the hash, but both links just link to # :S

      • jordanwallwork 9 years ago

        Ah forget that, as usual it's immediately obvious after I post that I don't understand! Looks like I had a bit of a mental block and couldn't see the top buttons for some reason - I was looking at the close links.

        Yup that all makes sense now then

awjr 9 years ago

Although I think this is an interesting exercise, I need these behaviours to work the same across all browsers. This gets even more complicated within JavaScript apps where the state of the components is something I need to have fine grained control over.

Really cool and good to see what how powerful CSS3 is, but not sure how useful it is, particularly when I need this behaviour working on older mobile browsers.

drinchev 9 years ago

I'm still a huge fan of "If you can do something with CSS, avoid JS", but these days, working with React, everything is JS.

Although IMHO it makes logical sense to put the logic for the modal windows in the JS, not the CSS. And definitely easier for maintaining it.

  • zaidf 9 years ago

    JS is far more predictable than CSS.

    • drinchev 9 years ago

      CSS ( properly written ) is easier to debug than JS.

      • bennettfeely 9 years ago

        I write a lot of CSS and I would probably disagree.

        CSS has no console.log() for debugging, CSS often fails silently, and the demos in the link are more or less (albeit pretty neat) hacks, but don't use CSS features in the way the specifications intended.

        • drinchev 9 years ago

          My reasoning is that CSS is not a language, it's just a configuration file.

          It doesn't have a console.log, but it has `background: red`.

          JS as a language and as such ( especially it's callback / event-driven nature ) makes it harder to debug.

          • TimJYoung 9 years ago

            Yes, but with the browser debugger you can step through the JS code and visualize what it is doing. How can you visualize what is happening with CSS, short of debugging the internal browser code ?

        • iamtyce 9 years ago

          Huh? Linting and compilation pull up just about every problem in the writing of CSS. The rest are browser bugs / quirks.

        • afarrell 9 years ago

          Also no unit tests and a program model that is hard to make into a coherent mental model.

      • thecopy 9 years ago

        Is CSS ( properly written ) is easier to debug than JS ( properly written )?

      • kyriakos 9 years ago

        Easier to find the bug harder to fix I think. The problem is CSS has a global scope - you change one thing and breaks the whole site's layout. With javascript usually code affects more specific areas of the site/web app.

        • e12e 9 years ago

          > The problem is CSS has a global scope - you change one thing and breaks the whole site's layout.

          I know what you mean (I tried fighting the default Plone theme before the littering of various instances of !important got refactored out) - but it's also deeply ironic. It's Cascading Style Sheets - if you don't use the namespacing - you will have a bad day. Remember how bad javascript snippets based off of tweaked code that some old version of Dreaweaver had injected to a project some generations prior to the one you were working on was?

          Just as people "programmed" javascript without learning the language, so people did with CSS. And not just "hammer it with !important until it stops resisting" either.

          Simple example: today, if you want poor man's stand-alone component ; stick the html in a div (or other element) with a class of Mygreatcomponent, and style from there with direct parent/child-stuff. Sure, you need to do manual namespacing, but even if your project is huge, you can grep for class='whyisitallpinkComponent'.

        • praveenweb 9 years ago

          "The problem is CSS has a global scope". CSS can be written in a way that it affects only specific parts of the site/app. "you change one thing and breaks the whole site's layout". There are use-cases when you want changes to reflect across the entire site and CSS can be easily used to achieve it. (Ex: changing color of buttons). Javascript can also break the whole site's layout. It just depends on what code we write.

        • err4nt 9 years ago

          I experiment with scoped CSS - where styles and even responsive conditions are tied to a specific element on the page and not the page as a whole.

          This means you I'm able to retrofit old sites with new code with zero fear that the code I'm adding can affect anything else previously on the site :) It's also handy when building new stuff too.

        • malydok 9 years ago

          If you properly modularize your CSS the global scope no longer remains a concern.

          • kyriakos 9 years ago

            the thing is that we don't always start working on sites from scratch. more often I have to clean up someone else's mess or my own that I made months or years ago. in that case I'd rather debug javascript than css.

            • lloyd-christmas 9 years ago

              Yeah, I think it's a lot easier to fix shitty JS than it is to fix shitty CSS. Every job I've had, I've fixed more than I build. If it's a 5 person startup, I'm iteratively fixing my own shit as the product pivots. If it's 30 people, I'm fixing code from that one idiot that interviewed well and turned out to be impressively terrible. If it's a 10,000 person company, I'm fixing shit from that entire division that wasn't properly managed.

              • erlehmann_ 9 years ago

                On the contrary, I think it is a lot easier to fix shitty CSS than shitty JS, because CSS is not run, but specifies attributes. This makes analysis static for the most part; race conditions and similar bugs usually do not occur.

              • kyriakos 9 years ago

                my entire career in 2 lines

kyriakos 9 years ago

Using checkboxes and radio buttons for keeping state is hacky to say the least. At the end of the day you can do the same with a few lines of easier to understand javascript.

progval 9 years ago

Ironically, all of these links point to jsfiddle/codepen, which require Javascript to see the demo.

mxuribe 9 years ago

Traditionally, I remember the rule that presentation should be managed by css, while behavior should be managed by javascript. But does the fact that some things can be reasonably done either way change - for example - a site's or app's maintainability? How about it performance? Is a CSS implementation rendered faster than javascript? I struggle with this at times, especially in some cases where - admittedly older - frameworks allowed for some overlap. Ah, well, much like lots of the web, i'll just work to get stuff done.

  • hiou 9 years ago

    CSS animations and behaviors can be rendered outside the main JavaScript thread whereas JavaScript based animations cannot.

the_mitsuhiko 9 years ago

Whenever someone makes a menu with CSS instead of javascript i go crazy as a user. The lack of delay is such a frustration.

  • wtbob 9 years ago

    > Whenever someone makes a menu with CSS instead of javascript i go crazy as a user. The lack of delay is such a frustration.

    You like sluggishness?

    Whenever I see a menu with CSS, I'm delighted: it means I needn't enable JavaScript (which opens up my computer to infection) just in order to read a list of links.

  • huuu 9 years ago

    Fortunately you can use animation-delay to simulate bloated Javascript.

    • iLoch 9 years ago

      It's not about bloat, it's about accidentally triggering menus when you move your mouse down the page.

      • huuu 9 years ago

        Ah! I read the parent's post as sarcastic. But you are right, a little delay can be good.

        • scrollaway 9 years ago

          There's a lot more to this than just "a little delay" to avoid accidental triggers.

          Good menus are complex. In desktop toolkits, there is a lot of logic to ensure they are accessible and don't behave in annoying ways. For example, a high quality menu will have a certain leeway to trigger into and out of submenus so that you don't accidentally drift into the incorrect submenu should you make an error of a couple of pixels while navigating them. They will have various delays and margins in place so that you are able to move your mouse in straight lines rather than make awkward 90 degree turns.

          A good menu system will also be navigable with a keyboard-only and will have access keys to quickly jump to items within it.

          Everybody who is reinventing the wheel because they see a menu as a mere "styled list of links that shows on hover" is missing out on the decades of learned UX that desktop systems have gone through. I sigh whenever I read, as I have many times in these comments, about making menus in CSS so that it's accessible to the 0.001% that doesn't use JS, while shutting off the much more real percentage of users that can't use a mouse (users that don't generally have a choice in the matter - unlike those turning JS off).

          • tommorris 9 years ago

            > 0.001% that doesn't use JS

            https://gds.blog.gov.uk/2013/10/21/how-many-people-are-missi...

            1.1% of users don't see JavaScript enhancements. Most because it doesn't load, not because they've disabled it. Also, some people use browsers that don't support JavaScript, or their ISP filters JavaScript, or a whole bunch of other things.

            I'm not endorsing making menus in CSS. I'm just saying that it isn't "accessibility vs. people who turn JS off".

            As the link says: progressive enhancement is the solution to this.

            • scrollaway 9 years ago

              That article is very nice but you're not reading it correctly if your takeaway is that "1.1% of users would benefit more from a CSS menu than from a JS menu". GDS is the UK government - a large portion of that 1.1% is likely not loading the CSS either. Bots, crawlers, rss readers, etc. The 0.2% number is much closer to what you're looking for.

              And to repeat: Those that disable javascript have a choice in the matter. Accessibility isn't a matter of choice.

              • tommorris 9 years ago

                I didn't take that from it. See "I'm not endorsing making menus in CSS." I'm endorsing progressive enhancement.

                Those that disable JavaScript do have a choice in it, but those who don't have JavaScript because it has been disabled for them, or because they are using a device that doesn't support JavaScript, don't have a choice in the matter.

          • wtbob 9 years ago

            Good points, but surely all that knowledge could be encoded once into some CSS attributes, rather then rewritten every time for every JavaScript framework on every site?

      • e12e 9 years ago

        On the subject on accessibility, I just came across this - note the comment from Brad Martin:

        http://terrillthompson.com/blog/474

  • lifthrasiir 9 years ago

    Also no hover menu [1], please. In JavaScript hover menu is harder to make, but in CSS it is instant and much prone to abusing.

    [1] http://uxmovement.com/navigation/why-hover-menus-do-users-mo...

  • vegardx 9 years ago

    You can always use transitions to add the same effect. I personally enjoy when things open quickly, some people almost fetishize transitions to an absurd level.

    • toupeira 9 years ago

      The bigger problem is things disappearing too quickly, e.g. as soon as your mouse moves one pixel away from a CSS hover menu it's gone.

  • martin_a 9 years ago

    Using CSS to create a menu is just fine, because all the technical background needed is already there in HTML.

    There is no need to throw some crazy JavaScript stuff at a problem that does not even exist.

    Seems like lots of web developers have forgotten to keep it simple.

  • adrianN 9 years ago

    Whenever someone makes a menu with js I don't use the site because I browse without js.

    • the_mitsuhiko 9 years ago

      That's fine. Nobody forces you to use my applications and websites.

      • e12e 9 years ago

        Until you work for a government agency. Or the only supplier of a certain important service in an area. Etc.

        • Ralfp 9 years ago

          Until your agency's spec goes among the lines of "UI implemented in modern technologies (eg. React.js, Angular, Ember.js)".

          And no, I'm not making this up.

    • paradite 9 years ago

      Then you start adding exceptions for every single website you visit, such as http://cs.stackexchange.com/

acbabis 9 years ago

The biggest problem with these hacks isn't a preference for CSS over JS (which IMO is fine in moderation); it's the fact that they aren't keyboard or screenreader accessible. A person using a screenreader can't even navigate to the accordion (http://jsfiddle.net/yn4ls/), and if they could, it would tell them it's a form element.

  • Kluny 9 years ago

    Yeah, that's an uncool abuse of the checkbox element. I'd rather be conventional than clever when it comes to layout.

everydaypanos 9 years ago

Still not good enough. For example the popover/tooltip that pops up on hover is fixed right below the target. If for example the viewport/window is smaller than the available space it will "bleed" out of view. You still need javascript to place it properly, and javascript that manipulates :after and :before pseudo elements is not straightforward.. Just saying :)

  • LoSboccacc 9 years ago

    More to the point :target can only target one element at most, since fragment is unique.

    the other stuff ranges from clever tricks, like the label/checkbox modal, to stuff which would be a nightmare to maintain on a complex page

    • erlehmann_ 9 years ago

      I have found that this makes it actually easier to reason about web page state: It is represented by the current URL.

  • wanda 9 years ago

    Actually, you just need media queries.

nachtigall 9 years ago

Would be nice if this would list the minium browser versions required for each example.

jliptzin 9 years ago

Just because you can, doesn't mean you should.

dotdi 9 years ago

Look ma! I replaced a few lines of JS with a crap-ton of CSS.

ivanhoe 9 years ago

IMHO this is a big step back, what do you really gain by sacrificing semantics just to avoid a little js code? CSS was supposed to help us separate content and presentation, and adding a bunch of unneeded tags just to make these hacks work is the very opposite of that.

Fletch137 9 years ago

A fun exercise - while you might not _need_ JS, it's still the best option in a lot of cases.

I'd never even consider using most of these techniques in production - while they're interesting and showcase what CSS can do, they're practically unmaintainable.

MrPatan 9 years ago

The accordion example cheats a bit. The height of the items is fixed to 300px.

I don't know if it'd be possible with flexbox nowadays.

The usual max-height trick is not ideal, as the animation then doesn't have the right duration.

IanCal 9 years ago

So in the first modal example, the document contains both dialog windows at the same time.

Is that really what you want? Does that properly describe the content of your document?

BinaryIdiot 9 years ago

These are cool "CSS tricks" but I would seriously never allow someone to use these in a production web application.

- It's not an accessible solution in most cases (no keyboard navigation)

- The CSS classes are very and overly complex to the point where it's not intuitive at all what they're doing (honestly the code being intuitive is more important to me than any minor performance benefits that may be seen here)

brador 9 years ago

Not everyone is using the latest CSS standard browsers. Keep it simple for production code. It's easier to work with, support, and maintain.

wnevets 9 years ago

Is it wrong of me to not like using the css content property? I feel like actual content shouldn't be in css.

  • napworth 9 years ago

    It depends on context. If it's stylistic content, then I say it's reasonable. If it's the main body of your blog post, then maybe just wrap it in a <p> tag.

  • talmand 9 years ago

    I agree, it should be strictly limited to non-important styling needs. Recently someone had to go through our code base removing text from content properties in our CSS to make way for a future translation effort.

vzip 9 years ago

I've seen people create some beautiful things in pure CSS but often the code looks like a horrendous hack.

supernintendo 9 years ago

There are almost 300 comments here and no one has pointed out the obvious: these can be used within email templates where JavaScript is unavailable. For that reason alone, I think this is pretty cool.

But sure. Always use the right tool for the job, as they say, and for application logic that tool is not CSS.

vladootz 9 years ago

Even if you can do a lot of stuff in css, sometimes you shouldn't do them. Razvan Caliman from Adobe has some good points on this topic: https://youtu.be/WupAsZGHDcY

amelius 9 years ago

> Css is more powerful today and you can do a lot of thing dont need js

Yes, but the problem is that adding or changing functionality implemented in CSS can easily lead you into a brick wall.

At that point you will either have to rethink your approach completely, or move back to JS.

imafish 9 years ago

In my opinion, using Cascading StyleSheets for this stuff is just broken. Animations are not styles. Behavior is not a style.

Readability and usability of animations could be improved by adding animation tags to the HTML Canvas (like WPF Storyboards: http://www.codeproject.com/Articles/364529/Animation-using-S...).

The view behavior-part could be done like WPF triggers. In fact let's just get rid of HTML/CSS and implement WPF for the browser.

vkjv 9 years ago

The accordion example isn't really what I think of as an accordion because it doesn't auto-close other elements.

For that behavior, you can make some minor tweaks swapping out the checkbox elements for radio buttons.

majewsky 9 years ago

I would like a superset of HTML that wraps these hacks up into nice controls, then compiles everything down to plain HTML + CSS.

curiousgal 9 years ago

I've always been told that the best way to learn something is to delve into it. Tried so with CSS but it was such a hassle that I gave up. Now, years later, all those past frustrations of my younger self remain to the point it's like a bête noire of mine. Seeing all this coolness makes me feel kinda bad for missing out. /rant

erlehmann_ 9 years ago

If I do not need JS, why do at least the first four demos do not work without it? I stopped trying the linked demos after that.

lucaspiller 9 years ago

Is it possible to display a "There are no records" message if a container is empty (i.e. tbody) using CSS only?

  • err4nt 9 years ago

    There is an :empty state you can use. I'm not looking at the demo right now but I've added messages like this:

        .container:empty:before {
          content: 'There are no Messages'
        }
    • dahauns 9 years ago

      Just be aware that the element really has to be empty - any whitespace (including empty child tags etc.) makes the selector ignore it.

      • err4nt 9 years ago

        Yeah, whitespace makes a textNode so an element containing any nodes can't be :empty. Also gotta watch out for those whitespace-only extra nodes when counting the children of an element with JavaScript, it often returns more children than you think at first ;)

drydenwilliams 9 years ago

It's a really nice solution for experiments but I've found it quite difficult to get people to adopt this CSS approach in some companies (regardless of any cross browser implications). Everyone needs to be on the same page and of course be up to date with CSS3 animations, which can be over looked.

josephjrobison 9 years ago

Related to this - is it possible to do something with pure CSS like shown in the black filter buttons area on this - http://www.siegemedia.com/creation/best-infographics ?

20years 9 years ago

While I don't think I would use a lot of this in production for the maintainability alone, it does showcase what you can do with CSS. I see a lot of convoluted Javascript being used on things that can easily and more cleanly be accomplished with a little CSS.

anacleto 9 years ago

You definitely missed the Pure CSS dancing tree: https://codepen.io/yukulele/pen/KCvbi

wehadfun 9 years ago

I''m glad that the general consent here seems to be doing this in CSS is not a great idea. I feel the same way about XAML where programmers try to do things in XML instead of C#

d33 9 years ago

On a side note, HTML + CSS3 is Turing complete:

https://news.ycombinator.com/item?id=2300836

nzjrs 9 years ago

Related, does anyone else have a preferred pure css treeview?

  • Piskvorrr 9 years ago

    Preferably one which does not require me to mouse down precisely to a 20px tall target, make a 90 degree turn, mouse right to another tiny target, turn again, repeat? And does not disappear on the tiniest error, making me go through the whole ordeal again?

    Also, keyboard support would be great. And if it wouldn't overflow offscreen.

    Oh wait, no such thing.

    (Note that these are basic issues, not arcane requests for 9-bit EBCDIC compatibility - but nooooo: let the users suffer, because we want to use this extra-cool trick)

iLoch 9 years ago

I think it would actually be wise to stick to JS style rendering (as is the case with React) as we're only going to see more and more styling being delegated to scripts with the rise of wasm. Only a matter of time before CSS will only really be useful for completely static websites IMO.

Edit: Downvoting me because you disagree isn't really in the spirit of HN.

Please provide a counter argument if you disagree, I'd be interested to hear it.

  • HelloNurse 9 years ago

    It would actually be wise to arm special forces with laptops, as we're only going to see more and more operations depending on hacking into security systems and building automation systems with the rise of smart devices that have no business being on the web (aka IoT). Only a matter of time before guns will only really be useful in third world countries without electricity.

    • Piskvorrr 9 years ago

      So, are you saying that a bunch of guys with wire cutters and guns would be unstoppable? Simple scenario:

      1. Cut all the power (grid connections A, B and C, disable generators) - nobody says no if you ask nicely and have a big gun 2. Watch the special teams struggle helplessly to hack into offline systems 3.PROFIT!!!

      Your assumption (that the network somehow runs on unicorn farts and that the need for boots-on-the-ground protection is obsolete) is fatally flawed. There's no way to outcloud everything, no matter how vigorously you try to handwave away the physical layer. Someone needs to keep the juice flowing, which also needs physical protection.

      • HelloNurse 9 years ago

        Not good at metaphorical sarcasm, eh? Special forces not using guns because they sometimes need hackers make as much sense as web developers not using CSS because they sometimes need Javascript-based layout.

        • Piskvorrr 9 years ago

          I was responding to this: "Only a matter of time before guns will only really be useful in third world countries without electricity" (emphasis mine) - still convinced that "issue not relevant at my level of abstraction" is not the same as "nonexistent".

reitoei 9 years ago

ITT: people taking this way too seriously

lasfter 9 years ago

It is pretty easy to cheat at the rocketship game by dragging your mouse to avoid enemies.

boubiyeah 9 years ago

Please don't. CSS is unmaintenable. JS can be made very maintainable; end of story.

hartator 9 years ago

I think that's great, but everything is based on hacks using checkboxes.

lsh 9 years ago

hm. ironically (?) none of the linked examples work without javascript.

ClassyJacket 9 years ago

Is that title supposed to be in English?

Keyboard Shortcuts

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