Svelte – Creating multiple components and adding CSS styles

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

Open Live Demo