·1 min read·教程

使用 CSS Grid 构建 Bento 布局

深入了解如何使用 CSS Grid 创建灵活的 Bento 风格网格布局,包括响应式设计和动画效果。

使用 CSS Grid 构建 Bento 布局

什么是 Bento 布局?#

Bento 布局灵感来自日本便当盒,特点是将内容分割成不同大小的模块,创造出视觉上有趣且功能性强的界面。

<Callout type="info"> Bento 布局在 Apple 的产品展示页面中被广泛使用,已成为现代 UI 设计的流行趋势。 </Callout>

基础网格设置

首先,我们需要创建一个基础的 CSS Grid 容器:

css
.bento-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 16px;
}

卡片尺寸系统

定义不同的卡片尺寸,使用 grid-columngrid-row 来控制:

typescript
type BentoCardSize = "1x1" | "2x1" | "1x2" | "2x2" | "3x1" | "3x2";

const sizeClasses: Record<BentoCardSize, string> = {
  "1x1": "col-span-1 row-span-1",
  "2x1": "col-span-2 row-span-1",
  "1x2": "col-span-1 row-span-2",
  "2x2": "col-span-2 row-span-2",
  "3x1": "col-span-3 row-span-1",
  "3x2": "col-span-3 row-span-2",
};

响应式设计

使用媒体查询适配不同屏幕尺寸:

css
/* 桌面端:4列 */
.bento-grid {
  grid-template-columns: repeat(4, 1fr);
}

/* 平板:3列 */
@media (max-width: 1024px) {
  .bento-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

/* 移动端:2列 */
@media (max-width: 768px) {
  .bento-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

毛玻璃效果

添加 Glassmorphism 效果让卡片更有层次感:

css
.glass {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 24px;
}
<Callout type="warning" title="浏览器兼容性"> `backdrop-filter` 在 Safari 中需要 `-webkit-` 前缀。部分旧版浏览器可能不支持此属性。 </Callout>

悬停动画

添加平滑的悬停效果:

css
.bento-card {
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1),
              border-color 0.3s ease;
}

.bento-card:hover {
  transform: translateY(-8px);
  border-color: rgba(0, 212, 255, 0.4);
}

完整组件示例

tsx
interface BentoCardProps {
  size?: BentoCardSize;
  children: React.ReactNode;
  className?: string;
}

export function BentoCard({
  size = "1x1",
  children,
  className
}: BentoCardProps) {
  return (
    <div className={`
      ${sizeClasses[size]}
      glass
      bento-card
      rounded-3xl
      p-6
      cursor-pointer
      ${className}
    `}>
      {children}
    </div>
  );
}

最佳实践

  1. 保持一致的间距 - 使用统一的 gap 值
  2. 注意视觉平衡 - 大卡片和小卡片合理搭配
  3. 考虑内容优先级 - 重要内容使用更大的卡片
  4. 测试响应式 - 确保在所有设备上都有良好体验

总结

Bento 布局是一种强大而灵活的设计模式,通过 CSS Grid 可以轻松实现。关键是要:

  • 定义清晰的尺寸系统
  • 实现响应式适配
  • 添加适当的视觉效果

希望这篇文章对你有帮助!

相关文章