简体   繁体   中英

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

I'm trying to center an empty CSS grid in a div. I need the grid to maintain a 16:9 aspect ratio and fill as much space as possible in the 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.

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; in the grid's CSS and place-content: center center; in the div's CSS, but both of those shrink the grid.

The container div does not have to be a grid if that makes it easier.

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

<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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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