如何动态获取/共享屏幕大小的网格项?

问题描述 投票:1回答:1

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

我怎么能让网格自动调整其中的元素以匹配当前viewport /页面的大小?

  • 如果只有一个,那么它应该是页面的大小
  • 如果有两个,那么它应该是宽度的一半并且是并排的
  • 第三行应该从第二行开始,是半高和全宽
  • 四个应该是1/4左右。

然后其余的趋势继续下去。

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

下面的代码与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回答了这个问题,但是,看到网格执行此任务也会很好。

html css css3 css-grid
1个回答
3
投票

您可以使用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>
© www.soinside.com 2019 - 2024. All rights reserved.