0

I'm using v2 of Nuxt.js.
If css is loaded under the following conditions, no style will be set on the child elements.

  • Import scss file with style settings with style tag
  • Add scoped to the style tag above.

Below is a demo.
CodeSandBox
It can be confirmed that the style for the elements under header in /assets/style.scss is not set.

header {
  background: #dddddd;

  > ul { // not working
    list-style: none;
    padding: 0;
    display: flex;
  }

  button { // not working
    background: black;
    color: white;
  }
}

Is there a way to style child elements in the form of importing scss?


The main codes are as follows.

<template>
  <div id="app">
    <Header />

    <HelloWorld />
  </div>
</template>

<script>
import Header from "./components/Header";
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    Header,
    HelloWorld,
  },
};
</script>

<style lang="scss" scoped>
@import "./assets/style.scss";
</style>
// Header.vue
<template>
  <header>
    <ul>
      <li>
        <h1>{{ appName }}</h1>
      </li>
      <li>
        <button>Sign in</button>
      </li>
    </ul>
  </header>
</template>
// style.scss

header {
  background: #dddddd;

  > ul {
    list-style: none;
    padding: 0;
    display: flex;
  }

  button {
    background: black;
    color: white;
  }
}

.hello {
  background: #efefef;
  padding: 1rem;
}
Ema
  • 27
  • 4

1 Answers1

0

Its CSS will apply to elements of the current component only. So you need to append below code

<style lang="scss" scoped>
@import "../assets/style.scss";
</style>

at Header.vue to make the css file effected.

Aaron
  • 26
  • 1
  • then it will import it twice, bloating out the CSS for no reason – Lawrence Cherone Aug 22 '22 at 10:40
  • of course you need to remove the css at App.vue. It's better to write css file for each components instead of writing them into a single file – Aaron Aug 22 '22 at 10:43
  • No matter how small the css file is, it is necessary to create a css file for each component, and we would like to avoid that method. – Ema Aug 22 '22 at 10:54
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 25 '22 at 14:22