跳至主要內容
版本:v8

CSS 變數

Ionic 元件使用 CSS 變數 建構,方便自訂應用程式。CSS 變數可讓值儲存在一個地方,然後在多個其他地方參考。它們也讓在執行階段動態變更 CSS 成為可能 (先前需要 CSS 預處理器)。CSS 變數讓覆寫 Ionic 元件以符合品牌或主題變得比以往更容易。

設定值

全域變數

CSS 變數可以在應用程式中的 :root 選擇器中全域設定。它們也可以僅適用於特定模式。如需 Ionic 提供的全域變數的詳細資訊,請參閱Ionic 變數

使用 Ionic CLI 啟動 Angular、React 或 Vue 專案時,會建立 src/theme/variables.scss 檔案,您可以在其中覆寫預設的 Ionic 變數。

/* Set variables for all modes */
:root {
/* Set the background of the entire app */
--ion-background-color: #ff3700;

/* Set the font family of the entire app */
--ion-font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', 'Roboto', sans-serif;
}

/* Set text color of the entire app for iOS only */
:root.ios {
--ion-text-color: #000;
}

/* Set text color of the entire app for Material Design only */
:root.md {
--ion-text-color: #222;
}

元件變數

若要設定特定元件的 CSS 變數,請將變數新增至其選擇器內。如需 Ionic 提供的元件層級變數的詳細資訊,請參閱Ionic 變數

/* Set the color on all ion-button elements */
ion-button {
--color: #222;
}

/* Set the background on an ion-button with the .fancy-button class */
.fancy-button {
--background: #00ff00;
}

透過 JavaScript 設定的變數

也可以使用 setProperty(),透過 JavaScript 變更 CSS 變數

const el = document.querySelector('.fancy-button');
el.style.setProperty('--background', '#36454f');

取得值

使用 CSS

如果需要,可以使用 var() CSS 函式來取得 CSS 變數的值,以及任何數量的回退值。在以下範例中,--background 屬性會設定為 --charcoal 變數的值 (如果已定義),如果未定義,則會使用 #36454f

.fancy-button {
--background: var(--charcoal, #36454f);
}

使用 JavaScript

可以使用 getPropertyValue(),在 JavaScript 中讀取 CSS 變數的值

const el = document.querySelector('.fancy-button');
const color = el.style.getPropertyValue('--background');

Ionic 變數

元件變數

Ionic 提供元件層級存在的變數,例如 --background--color。如需元件接受的自訂屬性清單,請檢視其API 參考CSS 自訂屬性區段。例如,請參閱按鈕 CSS 自訂屬性

全域變數

Ionic 提供幾個全域變數,以方便設定整個應用程式的主題。如需詳細資訊,請參閱顏色主題進階主題設定