在CSS网格中保持旋转的方形div的宽度和高度(响应解决方案) [英] Maintain width and height of rotated square divs in CSS grid (responsive solution)

查看:165
本文介绍了在CSS网格中保持旋转的方形div的宽度和高度(响应解决方案)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用跨设备的CSS网格来保持方形div的高度和宽度一致。我已旋转网格以尝试制作钻石 形状,但是当屏幕调整大小时,此形状会改变。如何在容器占据整个视口高度和宽度的网格中保持一致的完美旋转正方形宽度和高度?

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, but this shape changes when the screen resizes. How do I keep a consistent perfect rotated square width and height in my grid where the container takes up the entire viewport height and width?

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-column-gap: 1em;
  grid-row-gap: 1em;
  transform: rotate(45deg);
  overflow: hidden;
}

.grid>div {
  border: solid 1px red;
}

.container {
  width: 100%;
}

.grid {
  width: 100%;
  height: 100vh;
}

<div class="container">
  <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>
</div>

推荐答案

由于要旋转元素 45deg ,因此宽度/高度需要遵循以下公式: height = width = 50vh / cos(45deg)= 50vh / 0.707 。您还需要调整 transform-origin 并添加一个小的翻译以更正位置:

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>

translateY(-29%)是将左下角的原点移动到旋转前的左边缘:

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

蓝色距离等于 50vh-(100vh-宽度)= 50vh-100vh + 50vh / 0.707 = 50vh *(1 + 1.414)-50vh * 2 = 0.414 * 50vh

,如果将结果除以宽度( 0.414 / 1.414 ),我们得到 29%

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

这篇关于在CSS网格中保持旋转的方形div的宽度和高度(响应解决方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆