Future CSS: :drag (and Possibly ::dragged-image?)

You might be thinking, Another CSS pseudo-class? But I find this proposal quite interesting.

Earlier this year, a new pseudo-class, :drag, was proposed to allow developers to apply styles when an element is actively dragged by the user. Currently, CSS doesn’t have a way to detect drag interactions, making it hard to manage UI behaviors dependent on this action without JavaScript.

No JavaScript! I prefer a pseudo-class for this function over the classList.toggle() method.

But how would it work?

First, you need to understand the HTML Drag and Drop API. Some of the events it triggers include:

  • drag (fires every few milliseconds when the element is dragged),
  • dragstart (fires at the start of a drag), and
  • dragend (fires when dragging stops).

Let’s quickly see how these drag-and-drop events work in JavaScript to understand their potential CSS translation. Imagine seven button elements in a

:


  
  • We can make the .menu-bar draggable by adding an attribute:

    
      
    

    For CSS, we give the is-dragging class some styling, applied only when the element is dragged:

    .is-dragging {
      box-shadow: 0 4px 12px rgba(0 0 0 / 0.15);
      background: #fff;
      transform: translate(1px);
      opacity: 0.2;
      scale: 1.2;
    }

    Here’s the JavaScript to toggle between the start of the mouse drag and its end. It listens for a dragstart event and adds the .is-dragging class to the .menu-bar. When we drop the .menu-bar, dragging stops and the .is-dragging class is removed:

    menuBar.addEventListener("dragstart", (event) => {
      event.target.classList.add("is-dragging");
    });
    
    menuBar.addEventListener("dragend", (event) => {
      event.target.classList.remove("is-dragging");
    });

    Our output would look like this. Drag the dropdown element to see:

    Not bad! When the menu bar is dragged, it retains an image of itself in its original position styled with the .is-dragging

    Similar Posts