如何用CSS Grid实现2-6列及不对称比例布局?
使用CSS Grid实现不对称比例布局
嘿,我来帮你搞定这个CSS Grid的不对称布局问题!你提到的核心——定义子元素列宽,其实用Grid的fr(分数)单位就能轻松解决,它会自动根据可用空间按比例分配,比百分比更省心,还不用手动计算间距带来的影响。
下面针对你要的两种布局分别给出实现方案:
1. Two-Fifths - Three-Fifths(2/5 与 3/5 比例)
首先给容器设置Grid布局,然后通过grid-template-columns直接指定列的比例为2fr 3fr:
<h3>Two-Fifths - Three-Fifths</h3> <div class="cols cols-2-5"> <div class="two-fifths"> <p>This is an example of a WordPress post, you could edit this to put information about yourself or your site so readers know where you are coming from. You can create as many posts as you like in order to share with your readers what is on your mind.</p> </div> <div class="three-fifths"> <p>This is an example of a WordPress post, you could edit this to put information about yourself or your site so readers know where you are coming from. You can create as many posts as you like in order to share with your readers what is on your mind.</p> </div> </div>
/* 基础Grid容器样式 */ .cols { display: grid; gap: 2rem; /* 列之间的间距,可根据需求调整 */ margin-bottom: 2rem; } /* 2/5 与 3/5 比例的列设置 */ .cols-2-5 { grid-template-columns: 2fr 3fr; } /* 可选:给子元素加内边距和背景,方便看效果 */ .two-fifths, .three-fifths { padding: 1.5rem; background: #f5f5f5; border-radius: 4px; }
2. One-Sixth - Five-Sixths(1/6 与 5/6 比例)
原理和上面一样,只需要把grid-template-columns改成1fr 5fr就行:
<h3>One-Sixth - Five-Sixths</h3> <div class="cols cols-1-6"> <div class="one-sixth"> <p>This is an example of a WordPress post, you could edit this to put information about yourself or your site so readers know where you are coming from. You can create as many posts as you like in order to share with your readers what is on your mind.</p> </div> <div class="five-sixths"> <p>This is an example of a WordPress post, you could edit this to put information about yourself or your site so readers know where you are coming from. You can create as many posts as you like in order to share with your readers what is on your mind.</p> </div> </div>
/* 1/6 与 5/6 比例的列设置 */ .cols-1-6 { grid-template-columns: 1fr 5fr; } /* 可选:子元素样式 */ .one-sixth, .five-sixths { padding: 1.5rem; background: #f5f5f5; border-radius: 4px; }
额外说明:
fr单位会自动忽略gap的宽度,所以不用担心容器因为间距溢出,这比用百分比布局要方便得多。- 如果需要响应式布局,比如在移动端变成单列,只需要加个媒体查询:
@media (max-width: 768px) { .cols { grid-template-columns: 1fr; } } - 如果你不想给容器加不同的类,也可以直接给子元素指定
grid-column属性,但用grid-template-columns定义整体比例的方式更简洁直观。
内容的提问来源于stack exchange,提问作者user1678736
相关产品推荐
相关产品推荐

