Where is the uniapp css3 :root written?
Where is uniapp css3 :root written?
What is :root? Selectors
In CSS, the :root
pseudo-class selector is used to select the root element of the document, usually the <html>
tag. Using the :root
selector, you can declare global CSS variables, which will apply across the entire document. This makes it easy to manage styles in a unified way.
Usage in uni-app
uni-app is a cross-platform development framework based on Vue.js. It allows developers to write once and publish to multiple platforms, including WeChat mini-programs, HTML5, and apps. In uni-app, you can use the :root
selector to define global CSS variables, allowing you to manage styles across all platforms.
Where to write :root
at In uni-app, we can define :root
in the global CSS file to apply it to the entire app. In a uni-app project, there’s typically an App.vue
file and an App.vue
file in the same directory as App.vue
. We can define :root
directly in the App.vue
file.
Here’s an example:
/* App.vue */
:root {
--primary-color: #FF0000;
--secondary-color: #00FF00;
}
In this example, we define two global CSS variables, --primary-color
and --secondary-color
, to represent the primary and secondary colors, respectively. This allows us to use these variables throughout the application to set colors without having to specify specific color values each time.
How to Use Variables Defined with :root
Using variables defined with :root
is also very simple in uni-app. We simply reference these variables in our styles using var(--variable-name)
. Here’s an example:
/* styles.css */
.text-primary {
color: var(--primary-color);
}
.text-secondary {
color: var(--secondary-color);
}
In this example, we define two classes, .text-primary
and .text-secondary
, using the variables --primary-color
and --secondary-color
, respectively. By using these two classes in the HTML template, the color values defined in :root
will be automatically applied.
<!-- index.vue -->
<template>
<view class="text-primary">Primary Text</view>
<view class="text-secondary">Secondary Text</view>
</template>
<style lang="scss" src="./styles.css"></style>
In this example, we use the .text-primary
and .text-secondary
classes within a component’s template
to apply the color values defined in :root
.
Summary
Using :root
to define global CSS variables in uni-app is not complicated. Just write it in the global CSS