Maintain width and height of rotated square divs in CSS grid (responsive solution)

前端 未结 1 401
感情败类
感情败类 2021-01-22 10:25

I am trying to maintain a consistent height and width of my square divs using CSS grid across devices. I\'ve rotated the grid in an attempt to make a \'diamond\' shape,

相关标签:
1条回答
  • 2021-01-22 11:11

    Since you are rotating the element 45deg, the width/height need to follow this formula: height = width = 50vh / cos(45deg) = 50vh / 0.707. You need to also adjust the transform-origin and add a small translation to correct the position:

    .grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-column-gap: 1em;
      grid-row-gap: 1em;
      transform: translateY(-29%) rotate(45deg);
      transform-origin:bottom left;
      overflow: hidden;
      width:calc(50vh/0.707);
      height:calc(50vh/0.707);
    }
    
    .grid>div {
      border: solid 1px red;
    }
    
    body {
      margin: 0;
        overflow: hidden;
    }
    <div class="grid">
        <div>
          box
        </div>
        <div>
          box
        </div>
        <div>
          box
        </div>
        <div>
          box
        </div>
        <div>
          box
        </div>
        <div>
          box
        </div>
        <div>
          box
        </div>
        <div>
          box
        </div>
        <div>
          box
        </div>
      </div>

    The translateY(-29%) is to move the bottom left origin to the center of the left edge before the rotation:

    The blue distance is equal to 50vh - (100vh - Width) = 50vh - 100vh + 50vh/0.707 = 50vh*(1 + 1.414) - 50vh*2 = 0.414*50vh

    and if we divide this result with the width (0.414/1.414) we have our 29%.

    0 讨论(0)
提交回复
热议问题