我已经尝试了两天,就像在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百分比宽度,以便它们以砖块格式对齐并响应。然后我要给每个 child div一个背景图像。我的布局有效,但在某些 View 端口它会中断,最后一个子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>
我不明白,即使 child div的总和小于 parent 的100%,为什么他们仍在第二行移动。还有一件事...我正在尝试设计布局,以使子div的左侧或右侧没有空白。如果任何人都可以使用JavaScript / jQuery解决此问题,那对我也将起作用。
谢谢!
最佳答案
使用display:flex
可以更容易地创建类似于墙的“砖”,并且可以使用flex-grow
属性来控制容器的宽度比使用百分比更容易。
只是为了踢球,这是您可以使用的示例。在任何砖类型的flex-grow
上更改nth
值,您也可以创建更随机的模式。完全灵活。
加上Flex框,您可以在“砖块”上使用align-items
和justify-content
轻松控制文本对齐方式。
在提供的示例中,我们基本上将所有砖块都设置为flex-grow: 2
。因此,它们都是一样的,它们都将弯曲成相同的大小,并在每一行中占据相同的空间量。然后,我们可以使用伪选择器查找偶数行以及那些偶数行中的第一个和最后一个砖块,并制作flex-grow:1
(或两个的一半),以便在每一端制作一半的砖块。
.wall {
height: auto;
}
.row {
display: flex;
border-top: 2px solid white;
}
.row .brick {
flex-grow: 2;
}
.row .brick:not(:last-child) {
border-right: 2px solid white;
}
.row:nth-child(even) > .brick:first-child,
.row:nth-child(even) > .brick:last-child {
flex-grow: 1;
}
.brick {
display: flex;
justify-content: center;
align-items: center;
background-color: red;
height: 50px;
color: #fff;
font-family: Helvetica, sans-serif;
font-size: 12px;
}
<div class="wall">
<div class="row">
<div class="brick"></div>
<div class="brick">Lets</div>
<div class="brick"></div>
<div class="brick">Make</div>
<div class="brick"></div>
</div>
<div class="row">
<div class="brick"></div>
<div class="brick">The</div>
<div class="brick"></div>
<div class="brick">World</div>
<div class="brick"></div>
<div class="brick"></div>
</div>
<div class="row">
<div class="brick"></div>
<div class="brick"></div>
<div class="brick">Suck</div>
<div class="brick">Less</div>
<div class="brick"></div>
</div>
</div>