javascript - 如何在几个较小的相邻 div 上拥有一张大图像
问题描述
我有一堆类似表格的 div,如下所示:
这是 HTML:
<div id='container'>
<div class='row'>
<div class='smaller'>1</div><div class='smaller image'>2</div><div class='smaller image'>3</div><div class='smaller image'>4</div>
</div>
<div class='row'>
<div class='smaller'>5</div><div class='smaller image'>6</div><div class='smaller image'>7</div><div class='smaller image'>8</div>
</div>
<div class='row'>
<div class='smaller'>9</div><div class='smaller image'>10</div><div class='smaller image'>11</div><div class='smaller image'>12</div>
</div>
<div class='row'>
<div class='smaller'>13</div><div class='smaller'>14</div><div class='smaller '>15</div><div class='smaller '>16</div>
</div>
</div>
上面的图像布局是由以下 css 生成的:
#container {
background-color:yellow;
text-align: center;
}
#container .row .smaller {
background: white;
border: 1px solid grey;
display: inline-block;
width: 20%;
}
#container .row .smaller.image {
background: lightgrey;
}
可以根据需要轻松更换。
我需要将图像放在灰色的 div(2、3、4、6、7、8、10、11、12)上,以保持整个响应
正如在某处所读,我尝试了background-attachment: fixed;
向下滚动页面时不起作用的“”方法
如何做到这一点?
解决方案
It looks as though you have a grid, with the right hand upper items as one larger item.
If the image is to cover the items you have shown grayed out then there is no need to have them as separate cells and you can use CSS grid's template-area system to create the grid, with the image set as a background to the second cell.
Here's a simple snippet showing that. Note that the grayed out divs have been removed from the HTML as have the row divs as CSS grid will take care of that:
#container {
width: min(600px, 100vmin);
height: min(300px, 50vmin);
display: grid;
grid-template-areas: "A B B B" "C B B B" "D B B B" "E F G H";
}
#container>div {
display: flex;
justify-content: center;
align-items: center;
border-style: solid;
}
#container :nth-child(1) {
grid-area: A;
}
#container :nth-child(2) {
grid-area: B;
background-image: url(https://picsum.photos/id/1016/200/300);
background-size: cover;
background-position: center center;
}
#container :nth-child(3) {
grid-area: C;
}
#container :nth-child(4) {
grid-area: D;
}
#container :nth-child(5) {
grid-area: E;
}
#container :nth-child(6) {
grid-area: F;
}
#container :nth-child(7) {
grid-area: G;
}
#container :nth-child(8) {
grid-area: H;
}
<div id='container'>
<div>1</div>
<div>2</div>
<div>5</div>
<div>9</div>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
</div>
Obviously you will want to alter the sizes/aspect ratio of the container to suit your application.
推荐阅读
- vue.js - VueJS - 找不到模块
- javascript - 在箭头函数中的箭头之后使用 () 或 {} 有什么区别?
- parse-platform - 如何通过持续集成将更新部署到 Cloud Code?
- docker - 我只定义了一个 php docker,但是当我运行 docker-compose down 时,许多 php docker 停止了
- javascript - Nativescript 7 App 在 ios 中意外崩溃 == 断言失败 ==
- sql - 使用 HAVING COUNT> 子句进行查询
- python - 特定格式的字典
- python - 类型错误:+= 不支持的操作数类型:“int”和“str”。我一直在尝试调试此错误 20 分钟
- mapbox - 有没有办法遍历图层的所有功能并更改特定功能的样式?
- javascript - 生成唯一值和过滤数据对象