[英]How to Center Empty CSS Grid in Div and Maintain Aspect Ratio
我正在尝试将空的 CSS 网格置于 div 的中心。 我需要网格保持 16:9 的纵横比并在 div 中填充尽可能多的空间。 它是 div 中的唯一元素,并且 div 将更改大小,因为在完整文档中有可折叠的侧边栏和可折叠的 header。
下面的代码保持纵横比并填充空间,但是当我尝试将其居中时,网格缩小到最小尺寸。
我尝试使用place-self: center center;
在网格的 CSS 和place-content: center center;
在 div 的 CSS 中,但这两个都缩小了网格。
如果这样更容易,容器 div 不必是网格。
代码片段:
html, body { width: 100%; height: 100%; margin: 0px; }.container { width: 100%; height: 100%; display: grid; }.canvas-grid { border: solid red 3px; max-width: fit-content; max-height: fit-content; aspect-ratio: 16 / 9; margin: 5px; display: grid; grid-template-columns: repeat(16, 1fr); grid-template-rows: repeat(9, 1fr); grid-column-gap: 3px; grid-row-gap: 3px; }
<html> <link rel="stylesheet" href="styles.css"> <body> <div class="container"> <div class="canvas-grid"></div> </div> </body> </html>
试试100vh高度
<html>
<link rel="stylesheet" href="styles.css">
<body>
<div class="container">
<div class="canvas-grid"></div>
</div>
</body>
</html>
CSS:
html, body {
width: 100%; /* Does nothing, already 100% height by default */
height: 100%; /* 100% of auto does nothing */
margin: 0px;
}
.container {
width: 100%; /* div is block by default already takes up 100% width */
min-height: 100vh;
place-content: center;
display: grid;
}
.canvas-grid {
border: solid red 3px;
max-width: fit-content;
max-height: fit-content;
aspect-ratio: 16 / 9;
margin: 5px;
display: grid;
grid-template-columns: repeat(16, 1fr);
grid-template-rows: repeat(9, 1fr);
grid-column-gap: 3px;
grid-row-gap: 3px;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.