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>
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%
.
来源:https://stackoverflow.com/questions/54874997/maintain-width-and-height-of-rotated-square-divs-in-css-grid-responsive-solutio