Search code examples
javascripthtmlcssrotationglyph

How to apply CSS rotate transition around glyph's vertical middle or centerpoint


I have a hidden panel that sits off-screen until a div gets clicked (see attached, runnable code snippet).

When this div is clicked, the panel comes on screen and the div contents (a single glyph or character) are rotated 180 degrees.

The problem is that rotation origin is around some point other than the vertical middle of the glyph. When rotation occurs, the glyph moves up several pixels.

How can I measure the glyph attributes and set the rotation origin, so that, when it rotates, it rotates around the vertical middle or center of the glyph?

var show_panel = function() {
	var e = document.getElementById("panel");
	if (e.classList) {
		e.classList.toggle("show");
	}
    else {
	    var classes = e.className;
	    if (classes.indexOf("show") >= 0) {
		    e.className = classes.replace("show", "");
	    }
	    else {
		    e.className = classes + " show";
	    }
    }
};
body {
    margin: 0;
    padding: 0;
    overflow: hidden;
    font-family: system, -apple-system, ".SFNSDisplay-Regular", "Helvetica Neue", "Helvetica", sans-serif !important;
}

#panel {
  	width: 300px;
  	/* border: 2px solid rgba(33, 33, 33, 0.0933); */
  	background-color: rgba(33, 33, 33, 0.0933);
  	position: fixed;
  	top: 60px;
  	left: -275px;
  	padding: 5px;
  	-webkit-transition: all 0.5s ease-in-out;
  	-moz-transition: all 0.5s ease-in-out;
  	-o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

#panel.show {
  	left: -5px;
}

#panel .controller {
  	position: absolute;
  	right: 5px;
  	text-decoration: none;
  	color: black;
  	font-weight: bold;
    font-size: 2em;
  	-webkit-transition: all 0.5s ease-in-out;
  	-moz-transition: all 0.5s ease-in-out;
  	-o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

#panel.show .controller {
  	-webkit-transform: rotate(180deg);
  	-moz-transform: rotate(180deg);
  	-o-transform: rotate(180deg);
    transform: rotate(180deg);
}
<html lang="en">
  <body>
    <p class="panel_description">Click on the "x" to trigger showing the panel. Note how the "x" does not rotate on the vertical midpoint of the glyph, but instead moves upwards</p>
    <div id="panel">
      <div onclick="show_panel();" class="controller">x</div>
    </div>
  </body>
</html>


Solution

  • You can achieve it by setting css propertytransform-origin: 50% 50% it will provide transformation around the center of the element. I hope this works.