Skip to content

外观与主题

Mini App 支持自动适配用户的明暗主题,并提供丰富的主题颜色参数和 CSS 变量。

ThemeParams

ThemeParams 对象包含客户端当前主题的颜色参数。通过 Telegram.WebApp.themeParams 访问。

颜色属性

属性类型描述
bg_colorString背景颜色
text_colorString主要文字颜色
hint_colorString提示文字颜色
link_colorString链接颜色
button_colorString按钮背景颜色
button_text_colorString按钮文字颜色
secondary_bg_colorString次要背景颜色
header_bg_colorString标题栏背景颜色。Bot API 7.10+
bottom_bar_bg_colorString底部栏背景颜色。Bot API 7.10+
accent_text_colorString强调文字颜色。Bot API 7.10+
section_bg_colorString区块背景颜色。Bot API 7.10+
section_header_text_colorString区块标题文字颜色。Bot API 7.10+
section_separator_colorString区块分隔线颜色。Bot API 7.10+
subtitle_text_colorString副标题文字颜色。Bot API 7.10+
destructive_text_colorString危险操作文字颜色。Bot API 7.10+

CSS 变量

Mini App SDK 会自动将所有主题颜色注入为 CSS 变量,可直接在样式表中使用:

css
.my-element {
  background-color: var(--tg-theme-bg-color);
  color: var(--tg-theme-text-color);
}

.my-button {
  background-color: var(--tg-theme-button-color);
  color: var(--tg-theme-button-text-color);
}

.my-link {
  color: var(--tg-theme-link-color);
}

.my-hint {
  color: var(--tg-theme-hint-color);
}

完整 CSS 变量列表:

CSS 变量对应属性
--tg-theme-bg-colorbg_color
--tg-theme-text-colortext_color
--tg-theme-hint-colorhint_color
--tg-theme-link-colorlink_color
--tg-theme-button-colorbutton_color
--tg-theme-button-text-colorbutton_text_color
--tg-theme-secondary-bg-colorsecondary_bg_color
--tg-theme-header-bg-colorheader_bg_color
--tg-theme-bottom-bar-bg-colorbottom_bar_bg_color
--tg-theme-accent-text-coloraccent_text_color
--tg-theme-section-bg-colorsection_bg_color
--tg-theme-section-header-text-colorsection_header_text_color
--tg-theme-section-separator-colorsection_separator_color
--tg-theme-subtitle-text-colorsubtitle_text_color
--tg-theme-destructive-text-colordestructive_text_color

主题变化监听

javascript
Telegram.WebApp.onEvent('themeChanged', () => {
  const theme = Telegram.WebApp.themeParams;
  console.log('背景色:', theme.bg_color);
  console.log('主题模式:', Telegram.WebApp.colorScheme);
});

SafeAreaInset

SafeAreaInset 对象描述了设备安全区域的内边距(如刘海屏、圆角等区域)。通过 Telegram.WebApp.safeAreaInset 访问。Bot API 8.0+

属性类型描述
topInteger顶部安全区域内边距(像素)
bottomInteger底部安全区域内边距(像素)
leftInteger左侧安全区域内边距(像素)
rightInteger右侧安全区域内边距(像素)

示例

javascript
const inset = Telegram.WebApp.safeAreaInset;
document.body.style.paddingTop = inset.top + 'px';
document.body.style.paddingBottom = inset.bottom + 'px';

ContentSafeAreaInset

ContentSafeAreaInset 对象描述了内容安全区域的内边距(排除 Mini App 自身 UI 元素占用的空间)。通过 Telegram.WebApp.contentSafeAreaInset 访问。Bot API 8.0+

属性类型描述
topInteger顶部内容安全区域内边距(像素)
bottomInteger底部内容安全区域内边距(像素)
leftInteger左侧内容安全区域内边距(像素)
rightInteger右侧内容安全区域内边距(像素)

示例

javascript
const contentInset = Telegram.WebApp.contentSafeAreaInset;

// 结合设备安全区域使用
const safeInset = Telegram.WebApp.safeAreaInset;
const totalTop = safeInset.top + contentInset.top;

document.querySelector('.content').style.paddingTop = totalTop + 'px';