我正在尝试使用跨设备的CSS网格来保持方形div的高度和宽度一致。我已旋转网格以尝试制作'diamond'形状,但是当屏幕调整大小时,此形状会更改。如何在容器占据整个视口高度和宽度的网格中保持一致的完美旋转正方形宽度和高度?
.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>
答案 0 :(得分:2)
由于要旋转元素45deg
,因此宽度/高度必须遵循以下公式:height = width = 50vh / cos(45deg) = 50vh / 0.707
。您还需要调整transform-origin
并添加一小段平移以更正位置:
.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%)
将在旋转之前将左下角的原点移动到左边缘的中心:
蓝色距离等于50vh - (100vh - Width) = 50vh - 100vh + 50vh/0.707 = 50vh*(1 + 1.414) - 50vh*2 = 0.414*50vh
,如果将结果除以宽度(0.414/1.414
),我们得到29%
。