Strat 1: CSS pseudo-class


The simplest strategy: use the CSS :hover pseudo-class to change the style of the element under the cursor. Just a few lines of CSS and you're done.

Great for performance and easy to implement, but limited in design since it only affects the hovered element itself. Let's see how it works and when to use it.

Members only
5 minutes read

What is a pseudo class

A CSS pseudo-class is a keyword added to a CSS selector that specifies a special state of the selected element(s).

A CSS selector is a way to target specific elements in the DOM and customize them using CSS rules. For instance, h1 will target all level-1 headings in the document.

If you add the :hover keyword to the selector, the rules will be applied only when the element is hovered over!


Diagram showing how a CSS pseudo class works

Anatomy of a CSS rule using a pseudo-class


Give it a go! I've applied this rule to the title above. Hover over it to see it turn blue!

Application on a scatterplot

We can easily apply this technique to a scatterplot. Assign a class to each circle in the SVG area and use :hover to change its appearance:

.circle {
  fill-opacity: .3;
  stroke-width: 2px;
}

.circle:hover {
  fill-opacity: 1;
  stroke-width: 1px;
}

By default, each circle has a low opacity. On hover, the opacity jumps to 1 and the stroke becomes black — a small but noticeable change. Try it below:

import { data } from "./data";
import "./styles.css";

export default function App() {
  return (
    <svg width={430} height={320}>
      {data.map((d, i) => (
        <circle
          key={i}
          cx={d.x}
          cy={d.y}
          r={12}
          fill={d.color}
          className="circle"
        />
      ))}
    </svg>
  );
}

Hover over a circle to see the pseudo-class in action!

What property can you change?

There are several visual properties you can tweak to make a hovered point stand out.

Oh no! 😱

It seems like you haven't enrolled in the course yet!

Join many other students today and learn how to create bespoke, interactive graphs with d3.js and React!

Enrollment is currently closed. Join the waitlist to be notified when doors reopen:

Or Login