堆叠

堆叠负责在东西之间留出空隙。它是一个只干一件事的 flex 容器,也是「这几个怎么隔开」这类问题的通用答案——默认竖排,加上 direction: 'row' 就变成横排。

间隙取自间距尺度,所以整页的节奏保持一致,没人需要去挑像素值。

基础堆叠

第一个
第二个
第三个
stack({ gap: 'md' },
  card(cardBody('第一个')),
  card(cardBody('第二个')),
  card(cardBody('第三个')),
)

方向

stack({ direction: 'row', gap: 'md' },
  button('一'),
  button({ variant: 'outline' }, '二'),
  button({ variant: 'outline' }, '三'),
)

间隙

一个令牌名('xs' … '3xl')、若干个间距单位,或者一个原始 CSS 长度。

xsxsxs
mdmdmd
6 个单位6 个单位
3rem3rem
stack({ gap: 'lg' },
  stack({ direction: 'row', gap: 'xs' }, chip('xs'), chip('xs'), chip('xs')),
  stack({ direction: 'row', gap: 'md' }, chip('md'), chip('md'), chip('md')),
  stack({ direction: 'row', gap: 6 }, chip('6 个单位'), chip('6 个单位')),
  stack({ direction: 'row', gap: '3rem' }, chip('3rem'), chip('3rem')),
)

对齐

align 和 justify 直接接受 flexbox 的原始取值,所以 CSS 认得的写法都能用。

起始末尾
并且对齐
stack({ gap: 'md' },
  stack({ direction: 'row', gap: 'sm', justify: 'space-between', style: 'background: var(--su-surface-2); padding: 0.6rem; border-radius: 0.5rem' },
    chip('起始'),
    chip('末尾'),
  ),
  stack({ direction: 'row', gap: 'sm', justify: 'center', align: 'center', style: 'background: var(--su-surface-2); padding: 0.6rem; border-radius: 0.5rem' },
    button({ size: 'sm' }, '居中'),
    chip('并且对齐'),
  ),
)

换行

一排可能放不下的标签片或按钮需要 wrap——不加它,它们会被挤扁,而不是换到下一行。

routingdataislandsimagespagefindlighthousesitemaprss
stack({ direction: 'row', gap: 'sm', wrap: true },
  ...['routing', 'data', 'islands', 'images', 'pagefind', 'lighthouse', 'sitemap', 'rss'].map(
    (name) => chip({ color: 'neutral' }, name),
  ),
)

行内

inline 会把堆叠变成 inline-flex,于是它落在一行文字之中,而不是占满整行宽度。

用

sitelovite
搭起来,别的什么都没用。

text(
  '用 ',
  stack({ direction: 'row', gap: 'xs', inline: true, align: 'center' },
    chip({ color: 'primary', size: 'sm' }, 'sitelo'),
    chip({ color: 'neutral', size: 'sm' }, 'vite'),
  ),
  ' 搭起来,别的什么都没用。',
)

渲染为其他元素

stack({ as: 'nav', direction: 'row', gap: 'sm' },
  navLink({ href: '/zh/docs' }, '文档'),
  navLink({ href: '/zh/ui', current: true }, 'UI'),
  navLink({ href: '/zh/examples' }, '示例'),
)

属性

属性类型默认值说明
direction'row' | 'column''column'主轴方向。
gapSpace'md'子元素之间的间距。
alignstring'stretch'任意 align-items 值。
justifystring'flex-start'任意 justify-content 值。
wrapboolean | stringfalsetrue 表示换行;传字符串则原样当作 flex-wrap。
inlinebooleanfalse渲染成 inline-flex。
asstring'div'渲染成哪个元素,比如 nav 或 ul。