[英]Overwrite Bootstrap 4 Sass variables with CSS variables?
我正在嘗試使用 Angular 應用程序中的 CSS 變量將 Bootstrap 4 中的默認 Primary Sass 變量覆蓋為自定義顏色,如下所示:
樣式.scss
:root {
--primary: #00695c;
}
$myPrimary: var(--primary);
$primary: $myPrimary; // This does not work
@import '../node_modules/bootstrap/scss/bootstrap';
編譯我的應用程序時出現此錯誤:
Failed to compile.
./src/styles.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--15-3!./src/styles.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
undefined
^
$color: var(--primary) is not a color.
╷
181 │ $link-hover-color: darken($link-color, 15%) !default;
│ ^^^^^^^^^^^^^^^^^^^^^^^^
╵
node_modules\bootstrap\scss\_variables.scss 181:43 @import
node_modules\bootstrap\scss\bootstrap.scss 9:9 @import
stdin 19:9 root stylesheet
in C:\Work\node_modules\bootstrap\scss\_variables.scss (line 181, column 43)
有沒有辦法解決這個問題並使用css變量覆蓋bootstrap sass變量?
還有另一個相關問題,但我無法解決我的問題。
更新
實際上我已經創建了一個內部使用的 Angular 組件庫。 我已經使用 CSS 變量在這個庫中實現了主題化,因此我可以動態更改它們的值並允許用戶為應用程序選擇一個主題。
因此,在我的庫中,我有不同的主題文件,以下是其中之一:
主題.scss
@import './library-styles-to-be-used-in-app.scss';
:root {
--primary: #00695c;
--secondary: #f4f5f6;
}
現在,我將這個主題文件導入到我的 angular 應用程序style.scss文件中,如下所示:
@import '../dist/library/styles/theme.scss';
@import '../node_modules/bootstrap/scss/bootstrap';
請看下面的圖片 bootstrap css 變量已經被覆蓋,但是如果我使用像btn btn-primary
這樣的 bootstrap 類,它仍然顯示舊的藍色。
這是不可能的,因為 CSS 自定義屬性和 SASS 變量是兩個獨立的東西。
CSS 自定義屬性可以在運行時通過 Javascript 更改。
另一方面,SASS 變量是靜態的,它們將被生成,然后是.css
文件中的硬編碼值。 例如,SASS 的darken()
功能采用輸入字符串(例如十六進制值)並輸出此十六進制值的變暗版本。
但是 bootstrap 已經使用了 CSS 自定義屬性,所以也許您只是以錯誤的方式使用它們。 也許如果您擴展您想要實現的目標,也許我們可以更好地幫助您。
目前我們可以給你的唯一答案是:這是不可能的。
當前 SCSS 文件中的表達式(公式)不允許使用此技術。
有一個 github 問題可以將這些表達式從 SCSS 樣式移出並允許通過單獨的變量https://github.com/twbs/bootstrap/issues/31538進行設置,例如,您可以看到一個 PR,其中顯示了需要進行哪些更改在 Bootstrap 中以及如何為警報組件啟用 CSS 變量模式https://github.com/twbs/bootstrap/pull/31753
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.