Hacker News new | past | comments | ask | show | jobs | submit login
Two examples of hover styles on images (alexwlchan.net)
41 points by speckx 3 months ago | hide | past | favorite | 56 comments



Toggling between greyscale and colour is nice, but often you want the colour to be visible by default, and greying something out when you hover over it incorrectly gives the impression something is disabled. It’s the opposite you want. In these circumstances, when there’s a collection of items, I find that it’s a nice effect to show the collection in colour to begin with, and when you hover over an item, the other items get slightly greyed out.


A good hover style reminds me of how fast and responsive our computers can be, if we let them. For example, I add a thicker underline when you hover over a link on this site, and it appears/disappears almost instantly as I move my cursor around. It feels snappy; it makes me smile.

Sigh. We managed to raise a generation for which an instant interaction on a 1000+MHz multi-core gpu-accelerated 1000+MB/s io system feels snappy and that’s special. Good job, goob job.

you could add a negative margin to offset the border, or an always-on transparent border that only changes colour when you hover – but those can interfere with other CSS rules

The worst part of CSS is its globalness. You can’t have two paddings sourced from different subsystems, can’t name a border so you could address it specifically (e.g. as in el:border(myhover) {background: <gradient>}). CSS is so poor and antipattern and nobody bats an eye. You write an article like this and already see all these fragile hacks advices coming in, normalized by years of stockholming through even most basic layouts.


We managed to raise a generation who think it's acceptable for JavaScript to be required in order to render a single page.

For some "web developers", this is literally how they create a page:

    import React from 'react';
    
    function App() {
        return (
            <div>
                <h1>Hello world!</h1>
                <p>This is my HTML page.</p>
            </div>
        );
    }
    
    export default App;


As someone who experienced the rise of JavaScript, CSS and modern frontend frameworks, your comment gives me a chuckle because I'm pretty sure using JavaScript for hover effects pre-dates the ability to do that reliably using CSS.


Yes, but it was called DHTML back then!

Added: And it was not a deliberate choice but kind of a necessity.


I remember using Flash for hover effects. People complain we are in a cycle reinventing the wheel but I rather like the current wheel over the old one.


Isn't this just pointing out that progress = functional -> declarative?


More like progress is figuring out the common patterns and offering shortcuts for them. The querySelector api for example was born from jquery's popularity.


And it makes sense for those shortcuts, in general, to migrate 'up' the stack, JS -> CSS, JS+CSS -> HTML.


Really? I always thought jQuery was just a shorthand for it cause it’s too long to type. And they really walked the DOM to look for an element? What an ugly runtime it was, ugh.

https://stackoverflow.com/questions/39979816/how-was-jquery-...


Before `querySelectorAll` there was Sizzle, which was the selector engine that was eventually spun out of jQuery itself:

https://github.com/jquery/sizzle

If you think that's wild, before there were dev tools in every browser, there was only Firebug (yes, there was only `alert` before that, we didn't even have `console.log`):

https://getfirebug.com/


I don’t see anything bad here, tbh (ignoring my acute allergy to react—alikes). The problem is not how they write. DX is a good thing. Interactivity too. The problem is what happens at runtime: fetch html, fetch script, fetch data multiple times. It should be fetch html which contains a script which contains all the necessary data and creates elements and sets handlers.


It's ironic because I'm sure this lament has been voiced in one way or another with every generation of developers.

Anyway, your comment feels like a straw man; I don't know anyone who actually believes what you're claiming, nor is this sentiment anywhere on HN. The closest things are discussions about whether your website should work with JS disabled whenever a too-clever website is linked.


Having worked in enterprise web development...

Nah they're right. There's developers, in major corporations right now, who literally have no idea that you can just put HTML in a container and who are so drunk on node.js that they LITERALLY DO NOT UNDERSTAND what something like nginx, traefik, or Caddy is for.

These people are building healthcare systems.


"The future is now, old man!"


I can't really knock it when no one is ever going to ask them to do anything else. HTML might as well be assembly. It's starting to feel pretty vestigial at this point, it's all just different colored divs and aria labels. Elements on the screen as a human would perceive them stopped mapping to single elements ages ago.

For some "systems developers" this is literally how they create a program:

    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
        println("Hello world.");
    }
GTK/Unity/WinForms, everyone has their working level of abstraction.


This is good argument, but also it's apples to oranges. You list GTK/Unity/informs where, I suppose, you refer to their GUI editors that output xml etc, and code just ties everything up, but you can drive all three with code only, and again end up placing every component by hand. Replace your prntln with " ImGui::Text("hello, world");" and you have GUI window on the screen.


> The worst part of CSS is its globalness.

But global-ness is what you want from design directives. You want all your buttons to look the same, your links consistent. You want to define your base fonts once and then not have to worry about it for the rest of the build. You want to have your vertical rhythm (line spacing) repeated on most pages. You want most pages to have the same background and foreground colours. CSS syntax gives you all that for free.

Giving multiple elements the same border definitions is easy:

    elem,
    another-elem,
    .some-class,
    #just-this-one {
        border: whatever;
        background: swoosh;
    }
When I look at the hoops you have to leap through to get the same behaviour using any of the frameworks, my mind reels. Build steps, runtime libraries, repeated syntaxes in the mark-up...

I accept that managing things like the shared border example can get fiddly. SASS made it easier; some flavour of react-plus-css-helper-library thing can make it easier, kinda, if you squint. But it's actually _very_ simple to write the basic core idea in plain CSS. Personally, I feel that the discipline required to manage larger CSS codebases isn't that different than the discipline required to write good JS or TS; we just have a habit of pretending we shouldn't need to do that and wishing someone else would (via a library, or changing the standards). I don't know why we're happy doing it in JS or TS, but not CSS.


That’s as easy as

  fooModule.*(x),
  bar(x),
  Math.floor(x) {
    if (x === 42) return “oops”;
    return thisfunc(x);
  }
Or as COMEFROM. The proper way for modularity is to import subtrees of declarations and have them applied explicitly.

  // elem.css
  elem {
    use border-bg from “./bbg.css”;
  }

  // html
  <div>
    import elem from “./elem.css”
    <elem/> // has it
  </div>
  <elem/> // doesn’t
I don’t want aspect-oriented/comefrom globalness. It is an antipattern and dead tech in which you have to runtime-debug an element to learn its properties in each case, cause there’s no single place to treewalk your logic from.


Your example is solving a different problem from mine. We can’t compare.

I was arguing that global declarations are useful. Your example is intentionally differentiatiating similar elements, and placing the specialisation inline with the DOM declaration.

So far these seem more like style preferences. I can’t infer the “anti-patterns” you’re concerned about, nor how your version solves them. Could you expand some?

Personally, I much prefer keeping the layout and style code out of my JS/behavior code. It makes both easier to read.


A line of code somewhere affects an element. That’s aspect.

A line of code affects an element if written locally. That’s lexical scoping.

You can only runtime-check with aspect. You can statically infer with lexical scoping, cause all effects are specified in that scope.

My second example is solving the same problem, adding a common border and background to an element declaration.

My first example is solving the same problem too, adding a common behavior to a set of functions.


Ok, I see. I'm still not sold. Static analysis can't prove it looks right, so you need to runtime check it anyway. By that point, you may as well runtime debug.

Lisp (and I think SmallTalk) give us a rich history of developing against the runtime. I don't see why we should avoid it in the browser. The dev tools are very good, and have been fairly good since the '00s.

In my current team, we type check our CSS-in-JS (CSS-in-TS I suppose). It doesn't add much value. It can't tell you if the style rules are compatible with each other, if they'll conflict, if the cascade will force an effect you didn't intend the current snippet to produce. I am sure you're going to tell me that CSS is bad because it allows that kind of problem... but that's how visual design works! Every element contributes to the whole. Designers work from the outside in, and also from the inside out, rebalancing and refactoring as they go. CSS is a fairly good analog of that.


It can't tell you if the style rules are compatible with each other, if they'll conflict, if the cascade will force an effect you didn't intend the current snippet to produce. I am sure you're going to tell me that CSS is bad because it allows that kind of problem...

Good, means I’m almost there! All true.

but that's how visual design works!

That’s how CSS works, not visual design. It mixes all together and you can’t even design a generic container because its customization will affect the inner content containing that type of a container. And all its custom margins will fight with its own margins-as-a-child. And you can’t properly outline it in-parent without reserving space in advance and dealing with shattered layout, or using half-baked “outline:”. This only worked for a non-recursive text. It was designed for text.

I have worked as a designer many years ago btw. Corel draw, pagemaker, autocad, etc. I could place elements, group them, place two groups by distance between centers of their main content groups, stick them to arbitrarily angled guidelines. I wasn’t the autocad guy (more corel + vba) but I’ve seen how people work with it. CSS is like a $0.5 paper doll dress-up toy compared to these industrial CNCs. It’s not a pinnacle of design, it’s below mediocre at best.

There are alternatives like constraints, alignments and so on that could be simply included into CSS next. But the stubborn sandcastle-model obsessed committee can’t add more than one practical thing per decade, because everyone will migrate asap. Their reasoning makes sense sometimes, but don’t try to put css on a pedestal, it’s a heavy tradeoff, not a win.


I'm not putting CSS on a pedestal, but the last 25 years of web adoption would suggest CSS helped. You can do quite a lot with it. There are new features being added all the time: some of them even look useful (I wouldn't know.. I've been supporting devices from 2016 for the past four years so I'm out of date).

Could those CAD packages auto flow live text around the objects? Could you dynamically add new objects to your presentation in response to data and user interaction, and have them lay out perfectly according to your rules?

The paddings issue can be fiddly, but a little discipline can help. You've got two different width-calculation schemes to choose from. Flex & grid remove the need for most margin-wrangling and layout hacks. You can create relationships between objects and parents, and rotate/scale/translate groups of objects in 3D. You can flow text around irregular shapes. You have LOTS of control over fonts these days (I can't keep up with all the new font rules).

It may not be the pinnacle, but it's quite a reasonable compromise that's very easy to get into (admittedly hard to master, but so is most coding).

> That’s how CSS works, not visual design.

Visual design definitely, often employs a set of top-down ideas/rules, modified by sub-rules and ad-hoc exceptions.

> It mixes all together and you can’t even design a generic container because its customization will affect the inner content containing that type of a container. And all its custom margins will fight with its own margins-as-a-child.

If the paddings of your generic container don't suit some uses of that container, then maybe it's not as generic as you thought.

Also, this is pretty easy to do:

    .generic-ish {
      some: rule;
    }

    .generic-ish > .generic-ish {
      some: !rule;
    }


Isn‘t that what the id selector is for?


Aren't you describing https://developer.mozilla.org/en-US/docs/Web/CSS/outline?

> Outline is a line outside of the element's border. Unlike other areas of the box, outlines don't take up space, so they don't affect the layout of the document in any way.

If you s/border/outline in the dev console on the image you get what you want.


Outline is used for :focus and :focus-visible, so box-shadow is nice to have for hover so you don't have to repurpose the outline for it.


Is there any directive against defining an outline for :hover?


No, but when tabbing it's often more usable to have the outline look the same across different types of elements, and having a separate focus style from hover style makes it easier.


it seems to me that :hover and :focus are doing the same job in this case - indicating the target of the next action. I don’t see this as “repurposing”.


It's already been mentioned that instead of box-shadow perhaps outline is a better choice for the image frame.

For the icons, I don't understand why the author believes that they need to have two copies of the icon inside the SVG. You can style every property of every element using CSS. If your icon is a single path element, it should remain a path element and be styled something like this:

  svg.social path { fill: gray; }
  svg.social:hover path { fill: #8df; }
Of course it's possible that I'm missing something, but if all you want is changing color on hover, duplicating the item and using a mask is overkill.


I think that only works when the svg is embedded in the html, not when it's pulled in from a separate file through something like an <img> tag.


Although that's a good call as I hadn't considered that, I still don't see why you want to use a mask. Surely you just need two tiny SVG files and show only one or the other. And since they're tiny, I would absolutely embed them directly, which is why I didn't consider the case of an img tag.


Yep, does only work with embedded SVG and not for foreign resources.


The social icons are neat, but using filter would be shorter than manually setting normal and hover styles, at the cost of having inconsistent gray colors:

  .icon:not(:hover) {
    filter: grayscale(1);
  }


SVG elements also support currentColor for the fill property, which is linked to CSS’s color property.

<svg><path d=“” fill=“currentColor” /></svg>

element { color: hsl(0 0% 0%) }

One advantage is that you can target the parent element and the SVG will change automatically.

You can also create multiple “shades” by having currentColor on multiple paths with different opacity.


> at the cost of having inconsistent gray colors

Which, to be fair, is a pretty high cost. The consistency of the greys that only differentiate on hover is half the aesthetic value of the effect.


Also this would not work for GitHub, for example, where the hover color is black, which is already "grayscale".


Why go for the simple method when you can instead simply hand-edit SVG code then add two extra HTML elements per icon?


Use outline instead:

  outline: solid 10px red;
Nearly identical to border, but without affecting layout at all.


The CSS outline property is (was?) unreliable on Safari. Things like the border-radius don't affect the outline shape -- it's always square even if you to to create some Apple-patented rounded rectangles using border-radius.


Why this over box-shadow?


That’s why do you use `border-color: transparent` instead


That can make the image take up excessive space, or as the article says:

> ..., or an always-on transparent border that only changes colour when you hover – but those can interfere with other CSS rules


outline would seem to be the most appropriate solution here, unless I'm missing something.


Yes, you are right


Always nice to see CSS on here, but we figured this out 15yrs ago. Are the kids rediscovering hover styles?


You haven't noticed? Literally everything in web development has been in a constant cycle. Everything is reinvented and made significantly worse.

Next week: How to run your Docker React Node Babel Webpack Svelte grocery list application at the EDGE using Kubernetes on AWS serverless EC2 instances with Cloudflare workers.

EDIT: I forgot we're gonna use Bootstrap too.


Bootstrap? So passé. Just sprinkle in a dash of Tailwind:

<button class="bg-blue-600 px-4 py-3 text-center text-sm font-semibold inline-block text-white cursor-pointer uppercase transition duration-200 ease-in-out rounded-md hover:bg-blue-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2 active:scale-95">Hello world!</button>


Oh my god it’s so modern and innovative, can you imagine living in the past when you couldn’t simply define an element’s entire style block right there in the tag itself??


I really miss hover effects on mobile, wish there was a way for this !


There were / are / will be devices that support detecting hovering a finger or stylus away from the screen, so engineering-wise it's possible; it's just not included in the UX guidelines for the respective platforms.


It could also be implemented with eye tracking.


You can use :active, which should work when you press the button. You can still move your finger and release outside the button to avoid the interaction. The only problem is the finger covering the effect.


Short-press and scroll a little, this usually starts :hover mode. You’ve probably seen it accidentally triggering previews on various video platforms.

It works in TFA.


like so

  img{border: 10px solid transparent;transition:border 0.3s}
  a:hover img{border: 10px solid red;}




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: