Shopify自定义图片区块排版异常,需实现每行3图布局
问题原因分析
- HTML结构错误:
{% for block in section.blocks %}循环位置不正确,导致所有<div class="col">都被平级放在.gallery容器内,加上.gallery设置了display: flex,所有图片容器会一直横向排列,不会自动换行。 - CSS缺少布局规则:原
.gallery仅设置了display: flex,未定义图片容器的宽度占比和换行逻辑,无法实现每行3张的布局效果。
修正后的完整代码
<div class="gallery"> {% for block in section.blocks %} <div class="image-row"> <div class="image-col"> <div class="image"> <img src="{{ block.settings.editorial_image | img_url: 'master' }}"> </div> </div> <div class="image-col"> <div class="image"> <img src="{{ block.settings.editorial_image2 | img_url: 'master' }}"> </div> </div> <div class="image-col"> <div class="image"> <img src="{{ block.settings.editorial_image3 | img_url: 'master' }}"> </div> </div> </div> {% endfor %} </div> {% schema %} { "name": "EditorialTest2", "tag": "section", "class": "gallery", "max_blocks": 9, "settings": [ { "type": "text", "id": "title", "label": "Editorial" } ], "blocks": [ { "name": "PictureBlock", "type": "slide", "settings": [ { "type": "image_picker", "id": "editorial_image", "label": "Image" }, { "type": "image_picker", "id": "editorial_image2", "label": "Image" }, { "type": "image_picker", "id": "editorial_image3", "label": "Image" } ] } ], "presets": [ { "name": "Editorial Section Test 2" } ] } {% endschema %} <style> .gallery .image-row { display: flex; margin: 0 -8px; margin-bottom: 16px; } .gallery .image-col { flex: 1; padding: 0 8px; } @media only screen and (max-width: 560px) { .gallery .image-row { flex-direction: column; margin: 0; } .gallery .image-col { padding: 0; margin-bottom: 16px; } } .image img { width: 100%; display: block; } </style>
关键修改说明
- 重构HTML结构:将每个区块的3个图片容器包裹在
.image-row内,把循环放在最外层,确保每个区块对应独立的一行。 - 优化CSS布局:
- 给
.image-row设置display: flex,让同一区块的3张图片横向排列。 - 用
flex: 1让每个.image-col平分行宽度,保证每行3张图片尺寸一致。 - 添加间距控制提升视觉效果,移动端自动切换为纵向排列。
- 给
- 修复图片间隙:给图片添加
display: block,消除img标签默认的行内元素底部间隙。
内容的提问来源于stack exchange,提问作者saidakl
相关产品推荐
相关产品推荐

