html - 等宽和等高的flexbox
问题描述
我有两个关于弹性盒的问题,但找不到答案。
我想在不使用视口的情况下创建 4 个具有相同宽度和相同高度的框。例如:我创建了一个宽度为 50% 的盒子,高度需要等于宽度。所有其他框都具有相同的属性。
如果我有这些盒子,我想将 div 设置在其中一个正方形内,一个需要 20% 的高度和该盒子的整个宽度的盒子。如何将高度设置为 20% 并确保框不会延伸?
到目前为止我的代码:
.flex-container {
float: none;
width: 50%;
padding: 0;
margin: 0;
list-style: none;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -moz-flex;
display: -webkit-flex;
display: flex;
-webkit-flex-wrap: wrap;
flex-wrap: wrap;
}
.flex-item {
width: 50%;
color: white;
}
.flex1 {
background-color: green;
float: left;
}
.flex2 {
background-color: red;
float: right;
}
.flex3 {
background-color: purple;
float: left;
}
.flex4 {
background-color: orange;
float: right;
}
.inlineBox {
width: 100%;
height: 20%;
background-color: yellow;
}
<ul class="flex-container">
<li class="flex-item flex1">this boxes that I created here all need to have the same height and width. They need to be responsive and dont use a vieuwport</li>
<li class="flex-item flex2">2</li>
<li class="flex-item flex3">3</li>
<li class="flex-item flex4">4</li>
</ul>
<br>
<br>
<br>
these yellow box need to take a width of 100% and a height of 20% inside the flex box<br>
<ul class="flex-container">
<li class="flex-item flex1">
<div class="inlineBox"> </div>
<div class="inlineBox"> </div>
<div class="inlineBox"> </div>
</li>
<li class="flex-item flex2">2</li>
<li class="flex-item flex3">3</li>
<li class="flex-item flex4">4</li>
</ul>
解决方案
答案是不。原因在 flexbox 规范中提供: https ://www.w3.org/TR/css-flexbox-1/#flex-lines
您现在可以使用 display: grid:
https://codepen.io/pgurav/pen/eYpeOEp
虽然网格本身不是 flexbox,但它的行为与 flexbox 容器非常相似,并且网格内的项目可以是 flex。
如果您需要响应式网格,网格布局也非常方便。也就是说,如果您希望网格每行具有不同数量的列,则只需更改 grid-template-columns:
grid-template-columns: repeat(1, 1fr); /* 1 column */
grid-template-columns: repeat(2, 1fr); /* 2 columns */
grid-template-columns: repeat(3, 1fr); /* 3 columns */
等等...
您可以将其与媒体查询混合使用,并根据页面大小进行更改。
遗憾的是,仍然不支持浏览器中的容器查询/元素查询(开箱即用),以使其能够很好地根据容器大小而不是页面大小更改列数(这会很好用带有可重用的网络组件)。
有关网格布局的更多信息:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout
跨浏览器支持网格布局:
推荐阅读
- django - [Django]显示错误配置错误“需要 SQLite 3.8.3 或更高版本(找到 3.7.17)”,但在 manage.py runserver 中工作正常
- python - 将新版本上传到 TestPyPi
- ruby-on-rails - 更新没有从表单提交中获取所有参数
- python - 如何删除字符串列表中的所有空白元素?
- angularjs - Overriding the items in the json while using ng repeat
- javascript - 如何将来自 REST API 响应的数据存储在变量中?
- php - PHPMailer error "Message body empty" with Gmail
- c++ - 为什么在进行条件变量通知之前我们需要一个空的 std::lock_guard?
- sql-server - 在 SQL Server 中使用动态查询进行透视
- python - how to set environment variable from .env file in python script?