Reputation:
I'm currently learning Vue and can't get rid of a scope problem.
Question:
The profile.vue
styles keep overriding the ones from sidebar.vue
. The sidebar should keep it's red background with this setting, while the section in the profile page should be blue. Shouldn't do scoped
within the style
tag this job?
Profile.vue
below:
<template>
<main>
<section>
Test
</section>
<Sidebar></Sidebar>
</main>
</template>
<script>
import Sidebar from "../../components/sidebar/Sidebar";
export default {
name: "Profile",
components: {Sidebar}
}
</script>
<style scoped lang="scss">
main {
width: 100%;
@include flex();
section {
width: 100%;
background: blue;
margin-left: $size*5;
}
}
</style>
Sidebar.vue
below:
<template>
<section>
Test
</section>
</template>
<script>
export default {
name: "Sidebar"
}
</script>
<style scoped lang="scss">
section {
max-width: ($size*45);
width: 100%;
background: red;
}
</style>
Upvotes: 1
Views: 1125
Reputation: 331
Here are the docs explaining this behavior:
https://vue-loader.vuejs.org/guide/scoped-css.html#mixing-local-and-global-styles
This has already been answered here:
How to correctly use "scoped" styles in VueJS single file components?
Upvotes: 0
Reputation: 649
The problem here is that your child-component's root element is a section
By design, a parent component is able to style the child components root. In general this is used so you can easily style a child component, add margin, padding etc. But in your case it is conflicting.
What you see:
<template>
<div>
<section>...</section>
<your-component></your-component>
</div>
</template>
What your scoped css sees:
<template>
<div>
<!-- I can style out here -->
<section>...</section>
<section>
<!-- But I can't style in here -->
</section>
</div>
</template>
The scoped css knows not to go INTO the component, but the components root as basically at the level that it is allowed to style, and since it's a section, the css selector is valid.
If you just wrap your child component like this, there will be no conflict:
<template>
<div>
<section>...</section>
</div>
</template>
You can also style them with different classes etc.
Here is the official docs on it.
Upvotes: 3