html - 如何让网格项目动态适应/共享屏幕尺寸?
问题描述
我目前正在构建一个游戏,并想从我拥有的当前版本(在画布上运行)创建一个分屏并偶然发现 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 来回答,但是,很高兴看到网格也执行此任务。
解决方案
您可以使用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>
推荐阅读
- javascript - 固定位置不会在其他浏览器中保持固定
- c++ - 如何仅检测图像中烧杯内的水或溶液。(OPENCV)
- javascript - 使用 JavaScript 在 Chrome 中填写输入框
- jquery - Jquery pageload选择更改在移动设备上不起作用
- swift - 动态检查元类型一致性
- ubuntu-18.04 - Ubuntu 18.04 上的 zfs 传统挂载
- angular - 角度从 8 升级到 9 - 纱线不兼容错误
- python - 计算矩阵中每一行的最大值(不包括其自己的列)的更有效方法是什么?
- java - 我如何将 jooq 与 javers 一起使用?
- c# - C# Sqlite 没有更新