首页 > 解决方案 > 如何让网格项目动态适应/共享屏幕尺寸?

问题描述

我目前正在构建一个游戏,并想从我拥有的当前版本(在画布上运行)创建一个分屏并偶然发现

如何让网格自动调整其中的元素大小,使其与当前viewport/页面的大小相等?

然后趋势继续其余部分。

如果您熟悉分屏游戏,您可能知道我正在谈论的布局。

下面的代码在 4 个屏幕上完美运行;我不知道如何使用 1-2-3...-5-6-7 等来实现这一点。

.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr;
  padding-left: 0;
  padding-right: 0;
  margin-left: auto;
  margin-right: auto;
}

.wrapper canvas {
  width: 100%;
}
<div id="wrapper" class="wrapper">
  <canvas id="canvas" width="3840" height="2160"></canvas>
</div>

这个问题已经使用 flexbox 来回答,但是,很高兴看到网格也执行此任务。

标签: htmlcsscss-grid

解决方案


您可以使用Flexbox轻松完成:

body {display: flex; flex-wrap: wrap}

.flex {
  display: flex; /* displays flex-items (children) inline */
  flex-wrap: wrap; /* enables them to wrap (default: nowrap) */
  /* 16:9 ratio */
  width: 160px;
  height: 90px;
  margin: 5px;
}

.flex > div {
  flex-grow: 1; /* enabled (default: 0); can grow/expand beyond 50% of the parent's width */
  flex-basis: 50%; /* initial width set to 50% because none of the items will be less than that, no matter how many of them */
  border: 1px solid; /* just to see the result better */
  box-sizing: border-box; /* recommended because of the border; otherwise you'd need to use the CSS calc() function: "flex-basis: calc(50% - 2px);" -2px because of the left and right border, which is 1px each; same applies for margins, if you're going to use them, then you also need to use the calc(), e.g.: calc(x% - twice the defined margin) */
  background: #eff0f1;
}
<div class="flex">
  <div>1</div>
</div>

<div class="flex">
  <div>1</div>
  <div>2</div>
</div>

<div class="flex">
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>

<div class="flex">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

<div class="flex">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

<div class="flex">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>


推荐阅读