Search code examples
javascripthtmlcsscenter

Horizontally center rotated div in smaller parent


I want to horizontally center a -10 degree rotated div in a smaller parent.

I want this so that the middle point of the rotated div is in the center of the parent block. (I marked the middle point with some test text. But this is just to mark it).

How to go about this?

https://jsfiddle.net/ytL9ybww/3/

body {
      padding:0 0 0 0;
      margin: 0 0 0 0;
      padding-left:300px;
      overflow:hidden;
    }
    
    nav {
      height:100vh;
      width:300px;
      position:fixed;
      top:0;
      left:0;
      background-color:black;
    }
    
    .block {
      width:100%;
      position:relative;
      overflow:hidden;
    }
    
    .rotated-block {
      position:relative;
      z-index:10;
      top:300px;
      left:0;
      text-align:center;
      width: 5000px;
      height:900px;
      background-color:green;
      transform:rotate(-10deg);
    }
<div class="block">
  <nav>

  </nav>
  <div class="rotated-block">
    test
  </div>
</div>


Solution

  • First center the block (absolute positioning and a transform) then rotate it.

    .parent {
      height: 80vh;
      width: 80vw;
      margin: 1em auto;
      position: relative;
      border: 1px solid grey;
    }
    
    .child {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%) rotate(-10deg);
      background: red;
      width: 110%;
      height: 50px;
    }
    
    .center {
      position: absolute;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background: green;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    <div class="parent">
      <div class="child"></div>
      <div class="center"></div>
    </div>