简体   繁体   English

如何将 Div 中的空 CSS 网格居中并保持纵横比

[英]How to Center Empty CSS Grid in Div and Maintain Aspect Ratio

I'm trying to center an empty CSS grid in a div.我正在尝试将空的 CSS 网格置于 div 的中心。 I need the grid to maintain a 16:9 aspect ratio and fill as much space as possible in the div.我需要网格保持 16:9 的纵横比并在 div 中填充尽可能多的空间。 It is the only element in the div, and the div will change size since there are collapsible sidebars and a collapsible header in the full document.它是 div 中的唯一元素,并且 div 将更改大小,因为在完整文档中有可折叠的侧边栏和可折叠的 header。

The code below maintains the aspect ratio and fills the space, but when I try to center it the grid shrinks to the minimum size.下面的代码保持纵横比并填充空间,但是当我尝试将其居中时,网格缩小到最小尺寸。

I have tried to center using place-self: center center;我尝试使用place-self: center center; in the grid's CSS and place-content: center center;在网格的 CSS 和place-content: center center; in the div's CSS, but both of those shrink the grid.在 div 的 CSS 中,但这两个都缩小了网格。

The container div does not have to be a grid if that makes it easier.如果这样更容易,容器 div 不必是网格。

Code snippet:代码片段:

 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>

Try 100vh height试试100vh高度

<html>
  <link rel="stylesheet" href="styles.css">
  <body>
    <div class="container">
      <div class="canvas-grid"></div>
    </div>
  </body>
</html>

CSS: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM