求助:如何用CSS Grid与Flexbox实现6盒子网格布局
实现目标6盒子布局的解决方案
你当前的代码实现了均等尺寸的3列2行Grid布局,要实现目标的非均等6盒子布局,我们可以通过调整Grid的列定义,结合grid-column属性控制盒子的列跨度来完成,以下是修改后的完整代码:
<template> <div class="container"> <div class="row"> <div class="col text-center"> <h3>Best Of The Best</h3> <p>Sebuah lembaga pendidikan yang didedikasikan untuk memaksimalkan potensi anak bangsa.</p> </div> </div> <div class="hero-box-container"> <div class="hero-box hero-box-1">1</div> <div class="hero-box hero-box-2">2</div> <div class="hero-box hero-box-3">3</div> <div class="hero-box hero-box-4">4</div> <div class="hero-box hero-box-5">5</div> <div class="hero-box hero-box-6">6</div> </div> </div> </template> <script> export default { name: 'Hero', }; </script> <style scoped> .hero-box-container { display: grid; /* 定义4个等宽列 */ grid-template-columns: repeat(4, 1fr); /* 定义两行,第一行高度200px,第二行100px */ grid-template-rows: 200px 100px; /* 盒子间添加间距,可选 */ gap: 10px; padding: 10px; } .hero-box { /* 添加内边距和文字居中,提升视觉效果 */ padding: 1rem; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 1.2rem; } .hero-box-1 { background-color: #70e9c9; /* 占据第1到第3列(即前2个列宽) */ grid-column: 1 / 3; } .hero-box-2 { background-color: #63dbbb; /* 占据第3到第5列(即后2个列宽) */ grid-column: 3 / 5; } .hero-box-3 { background-color: #51c9a9; } .hero-box-4 { background-color: #3dafa0; } .hero-box-5 { background-color: #309d96; } .hero-box-6 { background-color: #1e897a; } </style>
关键知识点说明
repeat(4, 1fr):快速创建4个宽度均等的列,1fr表示分配剩余空间的1份,适配响应式布局。grid-column: 1 / 3:控制盒子从第1根网格线开始,到第3根网格线结束,即占据2个列的宽度。gap:设置盒子之间的间距,替代传统margin,写法更简洁。- 给
.hero-box添加flex属性,让内部文字自动居中,提升布局美观度。
如果你的目标布局不是这种“两大四小”的结构,只需调整grid-template-columns的列数,以及每个盒子的grid-column/grid-row跨度即可。比如要实现某盒子跨行,可用grid-row: 1 / 3让它占据两行高度。
内容的提问来源于stack exchange,提问作者As'ari
相关产品推荐
相关产品推荐

