[英]In React how to CSS reference variables in separate files
我有一個 react 項目,我插入了一堆變量,理想情況下我可以從其他 CSS 文件中引用這些變量,以便為某些 UI 配置(顏色、按鈕等)提供一個代碼庫。
雖然我不確定它是否應該在body{}
或:root{}
索引.css
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
margin: 0;
min-width: 100%;
min-height: 100%;
margin: 0;
padding: 0;
background-repeat: no-repeat;
background: var(--GradientLighterBlue);
--LightBlue:rgb(1,147,207);
--MediumBlue: rgb(1, 126, 207);
--DarkBlue: rgb(7, 101, 195);
--GradientLighterBlue: linear-gradient(0deg, rgba(1,126,207,1) 0%, rgba(1,147,207,1) 100%);
--GradientDarkerBlue: linear-gradient(0deg, rgba(7,101,195,1) 0%, rgba(0,72,144,1) 100%);
--LightYellow: rgb(252,177,52);
--MediumYellow: rgb(194,136,41);
--GradientYellow: linear-gradient(0deg, rgba(194,136,41,1) 0%, rgba(252,177,52,1) 100%);
}
我如何參考這些,例如。 例如home.css
中的var(--LightYellow)
?
在大多數情況下,將變量放在:root
元素或body
元素上沒有實際區別,因為所有可見元素都應該是 body 元素的后代,但將 放在根元素上是一個好習慣。
您可以從任何其他樣式表正常引用變量(即var(--LightBlue)
),而不管樣式表的順序如何,因為自定義屬性是繼承的。
使用 :root{} 聲明全局使用。
:root
和html
是對頂級元素的引用(它們是相同的)。 因此,您的css 變量應該存在以便在文件中全局使用:
/*
css-variable will be available everywhere
*/
html {
--LightBlue:rgb(1,147,207);
--MediumBlue: rgb(1, 126, 207);
}
如果您打開隨機網站(例如nextjs.org)並檢查html
標記,您會將他們的css 變量放在那里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.