跳到主要內容
+

CSS Baseline

CssBaseline 組件有助於啟動一個優雅、一致且簡潔的基礎,以便在其上構建。

全域重置

您可能熟悉 normalize.css,它是 HTML 元素和屬性樣式標準化的集合。

import * as React from 'react';
import CssBaseline from '@mui/material/CssBaseline';

export default function MyApp() {
  return (
    <React.Fragment>
      <CssBaseline />
      {/* The rest of your application */}
    </React.Fragment>
  );
}

子節點作用域

然而,您可能正在逐步將網站遷移到 Material UI,使用全域重置可能不是一個選項。可以通過使用 ScopedCssBaseline 組件,僅將基準應用於子節點。

import * as React from 'react';
import ScopedCssBaseline from '@mui/material/ScopedCssBaseline';
import MyApp from './MyApp';

export default function MyApp() {
  return (
    <ScopedCssBaseline>
      {/* The rest of your application */}
      <MyApp />
    </ScopedCssBaseline>
  );
}

⚠️ 請確保先導入 ScopedCssBaseline,以避免如上述範例中的 box-sizing 衝突。

方法

頁面

<html><body> 元素已更新,以提供更好的頁面範圍預設值。更具體地說

  • 已移除所有瀏覽器中的邊距。
  • 已套用預設的 Material Design 背景顏色。它針對標準裝置使用 theme.palette.background.default,而針對列印裝置使用白色背景。
  • 如果為 CssBaseline 提供了 enableColorScheme,則將通過在 <html> 上應用 color-scheme 來設定原生組件顏色。使用的值由主題屬性 theme.palette.mode 提供。

佈局

  • box-sizing<html> 元素上全域設定為 border-box。每個元素(包括 *::before*::after)都被宣告為繼承此屬性,這確保了元素的宣告寬度永遠不會因 padding 或 border 而超出。

捲軸

捲軸的顏色可以自訂以提高對比度(尤其是在 Windows 上)。將此程式碼添加到您的主題(用於深色模式)。

import darkScrollbar from '@mui/material/darkScrollbar';

const theme = createTheme({
  components: {
    MuiCssBaseline: {
      styleOverrides: (themeParam) => ({
        body: themeParam.palette.mode === 'dark' ? darkScrollbar() : null,
      }),
    },
  },
});

但是請注意,使用此工具(和自訂 -webkit-scrollbar)會強制 macOS 始終顯示捲軸。

色彩配置

此 API 在 @mui/material (v5.1.0) 中引入,用於在使用 color-scheme CSS 屬性等原生組件的 "light""dark" 模式之間切換。若要啟用它,您可以如下設定 enableColorScheme=true

<CssBaseline enableColorScheme />

// or

<ScopedCssBaseline enableColorScheme >
  {/* The rest of your application using color-scheme*/}
</ScopedCssBaseline>

排版

  • <html> 上未宣告基本字型大小,但假定為 16px(瀏覽器預設值)。您可以在 主題文件 頁面中了解有關更改 <html> 預設字型大小的更多資訊。
  • <body> 元素上設定 theme.typography.body1 樣式。
  • <b><strong> 元素的字體粗細設定為 theme.typography.fontWeightBold
  • 已啟用自訂字體平滑,以更好地顯示 Roboto 字體。

自訂

前往文件中的全域自訂章節,以變更這些組件的輸出。

API

請參閱以下文件,以獲取此處提及的組件可用的所有 props 和 classes 的完整參考。