Take the guesswork out of positioning an element with this CSS/'jQuery UI' hack (CSS pizza used for example)

Sorry if this is common knowledge but I’ve never heard of it.

The pen/demo:

How to use:
Open the pen in a new tab.
Move a pepperoni around.
Copy CSS that appears on the top left and paste it directly in the CSS section, overwriting elements as needed.
The pepperoni’s new default position is now where you last dragged it.
Note that dragging the pepperoni again after you already pasted the CSS will overwrite that CSS!

The best part? It’s completely responsive.

While I used a pizza as an example, this is applicable to practically any CSS shape that you’re trying to position along its parent. Perfect if you’re positioning something by eye. Nothing beats cold hard math if you want extreme accuracy, but this should give you an insight on whether there’s any pattern involved.

The JS function takes in two parameters: the element being moved, and the area of the html where the CSS output is placed.

  function dragAndShow($movable, $output) {

    $movable.draggable({
      drag: function() {

        var percentLeft = Math.round($(this).position().left / $(this).parent().width() * 1000) / 10 + "%";
        var percentRight = Math.round($(this).position().top / $(this).parent().height() * 1000) / 10 + "%";
        $output.html("#" + this.id + "{<br>&nbsp;&nbsp;position: absolute;<br>" +
          "&nbsp;&nbsp;left: " +
          percentLeft + ";<br>" + "&nbsp;&nbsp;top: " + percentRight + ";<br>}");
      }
    });
  }

Both parameters are jQuery DOM objects e.g.

dragAndShow($(".pepperoni"), $("#showPosition"));

Feel free to fork and play around with it.

1 Like