如何用CSS实现菜单区块分隔与2列3行菜单项布局?
菜单布局实现需求
我正在制作一个菜单,包含4个区块(section),每个区块有6个菜单项(food-item)。要求:
- 4个区块分别位于页面的四个角落
- 每个区块内的6个菜单项以2列3行的形式排列
我已创建对应的类名,当前效果为区块堆叠、菜单项垂直罗列,期望实现四角分布+网格排列的布局。
我的React组件代码
const Food = () => { return ( <div> <h2 className="AppHead">Appetizers</h2> <div className='whole-menu'> <div className="section"> {data.appetizers.map((food) => { return ( <div className="food-item"> {food.name} <span>- </span> {food.price} <p></p> {food.description} </div> ) })} </div> <div className="section"> {data.dishes.map((food) => { return ( <div className="food-item"> {food.name} <span>- </span> {food.price} <p></p> {food.description} </div> ) })} </div> <div className="section"> {data.desserts.map((food) => { return ( <div className="food-item"> {food.name} <span>- </span> {food.price} <p></p> {food.description} </div> ) })} </div> <div className="section"> {data.drinks.map((food) => { return ( <div className="food-item"> {food.name} <span>- </span> {food.price} <p></p> {food.description} </div> ) })} </div> </div> </div> ); }; export default Food;
实现期望效果的CSS代码
1. 容器基础样式
设置父容器为相对定位,作为区块定位的参考:
.whole-menu { position: relative; min-height: 80vh; /* 保证容器有足够高度容纳上下区块 */ padding: 2rem; }
2. 区块四角定位
通过nth-child选择器给每个区块设置绝对定位,分别放在四角:
/* 左上角区块 */ .section:nth-child(1) { position: absolute; top: 0; left: 2rem; } /* 右上角区块 */ .section:nth-child(2) { position: absolute; top: 0; right: 2rem; } /* 左下角区块 */ .section:nth-child(3) { position: absolute; bottom: 0; left: 2rem; } /* 右下角区块 */ .section:nth-child(4) { position: absolute; bottom: 0; right: 2rem; }
3. 菜单项2列3行布局
用CSS Grid实现每个区块内的菜单项排列:
.section { display: grid; grid-template-columns: repeat(2, 1fr); /* 2列等宽 */ gap: 1.5rem; /* 菜单项间距 */ width: 400px; /* 可根据需求调整区块宽度 */ } .food-item { padding: 0.5rem; line-height: 1.4; } /* 可选:添加上下分隔线优化视觉效果 */ .food-item:not(:last-child) { border-bottom: 1px dotted #ccc; padding-bottom: 0.5rem; }
4. 响应式适配(可选)
针对小屏幕设备调整布局,让区块堆叠、菜单项单列显示:
@media (max-width: 992px) { .whole-menu { position: static; min-height: auto; } .section:nth-child(n) { position: static; margin: 2rem 0; width: 100%; grid-template-columns: 1fr; /* 单列布局 */ } }
内容的提问来源于stack exchange,提问作者Kozan Tys
相关产品推荐
相关产品推荐

