如何获得网格项目以动态适合/共享屏幕尺寸?

时间:2018-08-31 22:18:42

标签: html css css3 css-grid

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

如何获取网格以自动调整其内部元素的大小,使其与当前viewport /页面的大小相等?

  • uf只有一个,那么它应该是页面的大小
  • 如果有两个,则宽度应为一半,并排
  • 第三行应从第二行开始,并且为一半的高度和全宽
  • 四个应该是周围的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回答,但是很高兴看到网格也执行此任务。

1 个答案:

答案 0 :(得分: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>

相关问题