In this article we will learn how to create multiple components in Svelte and import them. We will also see how to declare css styles and learn about their behavior of staying within component scope only.

Let’s first see how to declare styles –

<p>Hammer of Thor</p>

<style>
  p {
	color: purple;
	font-family: 'Comic Sans MS', cursive;
	font-size: 2em;
  }
</style>

This p tag style will only be applied in this component. If you import some other component here, they won’t inherit it.

Now we will see how to create another component. Suppose the second component is Superhero.svelte –

<script>
 const edith = 'Even dead, I am the hero'
</script>

<h3>Edith belonged to which Avenger?</h3>
<p>Ironman. Edith stands for <span class={'someClass'}>{edith}</span></p>

<style>
  h3{
    color: blue
  }
  p{
    color: brown
  }
  span.someClass{
    background: yellow
  }
</style>

Let’s import this file to above file –

<script>
  import Superhero from './Superhero';
</script>

<p>Hammer of Thor</p>

<Superhero />

<style>
  p {
	color: purple;
	font-family: 'Comic Sans MS', cursive;
	font-size: 2em;
  }
</style>

The rendered output will look like this –

Rendered output of nested component and styles in Svelte

Β Β Β Β Tweet this to help others

Live Demo

If demo doesn’t load here then use this link – https://codesandbox.io/embed/stoic-bartik-qm4ge

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles