Scoped CSS not being applied within the component
Cssvue.jsCss Problem Overview
I have the following form component:
<template>
<div>
<form>
<input placeholder="Recipe Name">
<textarea placeholder="Recipe Description..." rows="10"></textarea>
</form>
</div>
</template>
<script>
export default {
name: 'AddRecipeForm'
}
</script>
<style scoped>
form {
display: flex;
flex-direction: column;
}
</style>
The <style>
uses the scoped
attribute.
When applied, the CSS does not get loaded in. When scoped
is removed, it does get applied.
However I want to keep it local to the component.
Why is the CSS not getting applied when the scoped
attribute is present?
Css Solutions
Solution 1 - Css
It appears this was solved by doing a full-reload of the page. Hot reload should take care of scoped css.
However for future viewers, This is commonly asked when scoped CSS isnt being applied to a child component. This can be solved by using deep selectors. (e.g: Using a .selector >>> .desired-selector {}
)
EDIT: Since this is still getting activity, I'll bring my comment into the answer. ::v-deep
also works depending on what preprocessor you're using.
Solution 2 - Css
For some reason, scoped styles don't get applied during hot reload when they are first added to the component. Full page reload fixes the issue, from there the styles, since they have been detected, get updated with consecutive hot reloads.
Solution 3 - Css
Precisely same symptoms as the OP but none of the recommendations here so far have worked and I need to move on so our solution is to rely on CSS selectors normally:
- add a uniquely-named class to the top-level element below <template>
- prefix all scoped (non-global) selectors with that uniquely-named class
which had the unexpected but welcome upside when live-debugging our CSS is that the origin of the CSS rule is now obvious in devtools.
MyComponent.vue
<template>
<v-card class="MyComponent" ... >
<div class="fancyBox" ... >
/* ... */
</v-card>
</template>
<style>
.MyComponent .fancyBox { /* scoped to any MyComponent instance */ }
.globalBox { /* we wouldn't put a global style here, obv */ }
</style>
Yes, it's a pain to prefix component-scoped styles this way, but, at least it's a familiar thing to do and you get the added benefit in devtools of tracing the source of a style back to the component that declared it.
Caveat is that, of course, parent-scoped CSS will also bleed down to child-scopes. This, at least, is familiar CSS behaviour.
Solution 4 - Css
Rebuilding the Vue App by running 'yarn serve' has fixed the problem for me.