'Nuxt CSS properties declared on :root selector are not found
I have a Nuxt 2 app and I'd like to create a component with a <style>
tag like the following, using CSS properties for styling.
The goal is to define a default CSS property in the component that can be overridden from outside.
However, when I try this method, the default values don't seem to work at all.
<style lang="scss" scoped>
:root {
--default-badge-color: linear-gradient(90deg, #1717ff 0%, #bc29e0 92%);
--default-badge-text-color: #fff;
--default-badge-font-size: 1.6rem;
--default-badge-padding: 0.6rem 1rem;
--default-badge-border-radius: 16px;
}
.badge {
display: inline-flex;
align-items: center;
justify-content: center;
padding: var(--badge-padding, var(--default-badge-padding));
border-radius: var(--badge-border-radius, var(--default-badge-border-radius));
background: var(--badge-color, var(--default-badge-color));
color: var(--badge-text-color, var(--default-badge-text-color));
font-size: var(--badge-font-size, var(--default-badge-font-size));
text-align: center;
}
</style>
Do I have the wrong approach for the syntax?
EDIT: I corrected to padding: var(--badge-padding, var(--default-badge-padding))
. But the CSS properties are still not found except I define them inside .badge
.
Solution 1:[1]
It doesn't really make sense to scope :root
, which is intended to select the root of the document with higher specificity than the html
selector. That would be like scoping a style for <body>
.
Perhaps you're hoping :root
was a selector for the current component's root element (like :host
is for Shadow DOM), but there's no such pseudo-class in Vue. An alternative is to apply your own class to the component's root element, and use that as a selector:
<template> ?
<div class="my-root">
<div>...</div>
<div class="badge">...</div>
</div>
</template>
<style scoped>
?
.my-root {
/* CSS custom properties */
}
.badge {
/* styles using the CSS custom properties above */
}
</style>
On the other hand, if you really are trying to add CSS custom properties to the document root from within <style scoped>
, you can use the :global()
pseudo-class function on :root
:
<style scoped>
:global(:root) {
/* CSS custom properties */
}
.badge {
/* styles using the CSS custom properties above */
}
</style>
Or a separate global <style>
block just for :root
:
<style>
:root {
/* CSS custom properties */
}
</style>
<style scoped>
.badge {
/* styles using the CSS custom properties above */
}
</style>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | tony19 |