【发布时间】:2017-11-03 02:39:18
【问题描述】:
两天来,我一直在尝试在 CSS 中创建一个类似于附件图像的砖块布局,但没有任何成功。请看附图
为了实现这种布局,我编写了一些代码。我尝试使用以下 HTML 复制第一行(带有单词“Let's”的行)
<div class="photo-row first">
<div class="first-item-1"></div>
<div class="first-item-2"></div>
<div class="first-item-3"></div>
<div class="first-item-4"></div>
<div class="first-item-5"></div>
</div>
和 CSS
.photo-row {
width: 100%;
height: 200px;
}
.photo-row.first div {
display: inline-block;
height: 100%;
}
.first-item-1 {
width: 13.57%;
background: red;
}
.first-item-2 {
width: 19.21%;
background: green;
}
.first-item-3 {
width: 31.21%;
background: orange;
}
.first-item-4 {
width: 15.14%;
background: blue;
}
.first-item-5 {
width: 19.78%;
background: yellow;
}
我们的想法是为每个 div 赋予父 div 的固定百分比宽度,以便它们以砖块格式对齐并做出响应。然后我要给每个孩子 div 一个背景图像。我的布局有效,但在某些视口它会中断,最后一个子 div 移动到第二行。
我还制作了一个 codepen 演示来演示这一点:https://codepen.io/Ali_Farooq_/pen/oobBYj
.photo-row {
width: 100%;
height: 200px;
}
.photo-row.first div {
display: inline-block;
height: 100%;
}
.first-item-1 {
width: 13.57%;
background: red;
}
.first-item-2 {
width: 19.21%;
background: green;
}
.first-item-3 {
width: 31.21%;
background: orange;
}
.first-item-4 {
width: 15.14%;
background: blue;
}
.first-item-5 {
width: 19.78%;
background: yellow;
}
<div class="photo-row first">
<div class="first-item-1"></div>
<div class="first-item-2"></div>
<div class="first-item-3"></div>
<div class="first-item-4"></div>
<div class="first-item-5"></div>
</div>
我无法理解即使子 div 的总和小于父 div 的 100%,为什么它们会在第二行移动。还有一件事......我正在尝试设计布局,以便在子 div 的左侧或右侧没有空白。如果有人对此有 JavaScript/jQuery 的解决方案,那么这对我也有用。
谢谢!
【问题讨论】:
-
我会推荐这种布局的弹性框。
-
我绝对同意 flexbox 可能是正确的方法,但您可能还想看看 Grid Layout 看看它是否适合您。
-
Flexbox 很好,但并非所有浏览器都支持,CSS 网格也是如此。如果这是一个问题,您只需浮动元素以删除空格 -
float: left; -
我想说,在这一点上 flex box 得到了相当广泛的支持 (caniuse.com/#feat=flexbox)。解决浏览器中的已知问题(看看你的 IE ......)通常比使用传统的显示方法、浮点数和百分比提出解决方案更容易。
标签: javascript jquery html css