How to Style Svelte Applications

Web frameworks come and go, but one of the most promising is Svelte. Svelte is a great alternative to React and, although it already has a large community, its definitely a framework to watch out for. Svelte makes it easy to style your apps, with several approaches available.

Web frameworks come and go, but one of the most promising is Svelte. Svelte is a great alternative to React and, although it already has a large community, it’s definitely a framework to watch out for. Svelte makes it easy to style your apps, with several approaches available.

Styling Svelte Applications

Every UI library or framework requires a method to style its components. Most component-based frameworks support the traditional method of styling components: simply import the CSS file and you’re done. Svelte is no exception. In Svelte, there are three main ways to style your applications, each with its own advantages and disadvantages.

Setting Up Your Svelte Project

To install Svelte, you can use the ViteJS front-end build tool. To set things up, ensure that the Node.js runtime and the Node Package Manager (NPM) are correctly installed on your computer. You can verify the availability of Node.js and NPM by running this terminal following command:

node -v

After making sure that Node is running, open the terminal and run the following:

npm create vite

Or:

yarn create vite

This should scaffold a new Vite project. Set the project name to whatever you want, the framework should be "Svelte" and the variant should be JavaScript (but you can use TypeScript if you are comfortable with that). Now, switch to the project directory with the cd command and run the following command to install the necessary dependencies:

npm install

Or:

yarn

After installing the dependencies you can start the development server by running:

npm run dev

Or:

yarn dev

Defining the Markup of the Project

Open the project in any code editor of choice and delete the assets and lib folder. Also, make sure you clear the contents of the app.css file and the App.svelte file. Open the main.js file and replace the contents with the following:

import App from './App.svelte'

const app = new App({
  target: document.getElementById('app'),
})

export default app

Next, open the App.svelte file and in the script tag and create an array that will hold different links, like this:

<script>
  let imageLinks = [
    "https://images.pexels.com/photos/1170986/pexels-photo-1170986.jpeg",
    "https://images.pexels.com/photos/1754986/pexels-photo-1754986.jpeg",
    "https://images.pexels.com/photos/3257811/pexels-photo-3257811.jpeg",
    "https://images.pexels.com/photos/3643714/pexels-photo-3643714.jpeg",
    "https://images.pexels.com/photos/755834/pexels-photo-755834.jpeg",
    "https://images.pexels.com/photos/2928158/pexels-photo-2928158.jpeg",
  ];
</script>

Under the script tag, create a main element, with a child "container" div that will hold all the images. Then, iterate through every element in imageLinks and render an image element for each iteration.

<main>
  <h1>Cute Cat Gallery</h1>
  <h3>See the cutest images of cats from the internet</h3>
  <div class="container">
    {#each imageLinks as url}
      <div class="image-container">
        <img src={url} />
      </div>
    {/each}
  </div>
</main>

After defining the markup, you can now proceed to style the application with the first method—direct CSS imports.

Styling Svelte Components With Direct CSS Imports

One of the common ways to style a Svelte component is to write an external CSS file and import it directly into the component. At the top level in the script tag, import the app.css file like this:

import "./app.css";

Now, open the app.css file and set the display property on the "container" class to "grid", and set the padding on the "image-container" class to 10px:

.container {
  display: grid;
  grid-template-columns: 33.3% 33.3% 33.3%;
}

.image-container {
  padding:10px;
}

Select the images and make them responsive, then add the appropriate styling for hovered images:

img {
  max-width: 100%;
  height: auto;
  border-radius: 10px;
  transition: 250ms;
}

img:hover {
  scale: 1.03;
  transition: 250ms;
}

When you run the code in the browser, this is what you should see:

Advantages of Direct CSS Imports

  • Reusability: Defining your CSS in an external file, makes it easy to reuse the same styles across multiple components. This could come in handy in cases where you want different components to share the same styling.
  • Flexibility: If you decide to redesign your website, you can update the styling in the external CSS file without needing to modify the HTML structure. This separation of concerns allows for greater flexibility in adapting your site's design.

Disadvantages of Direct CSS Imports

  • Cascading Complexity: While defining your CSS in an external file is powerful, it can also lead to unexpected conflicts and overrides when external styles interact with each other. This can lead to time-consuming debugging and troubleshooting. You can prevent unexpected styling conflicts in Svelte by using style tags directly in the Svelte file.
  • Increased load time: When a user visits your website, they will need to download the external CSS file in addition to the HTML and optionally, JavaScript files. This can add a few milliseconds to the load time, which may not seem like much, but it can add up if you have a lot of external CSS files.

Styling Using Svelte Style Tags

The second way of styling Svelte components is using the style tags provided by Svelte. The syntax looks something like this:

<script>
  <!-- Your logic goes here -->
</script>

<!-- Markup goes here -->

<style>
  <!-- styling goes here -->
</style>

One advantage of this method is that it scopes styles to the component, meaning that styles from one component cannot affect the styles from another component. It is important to note that style tags in Svelte take the highest priority and will override any external CSS styling for a given element. To illustrate that, add the following to the end of the App.svelte file

<style>
h1 {
  background-color: red;
}
</style>

Then, add the following to the end of the App.css file:

h1 {
  background-color: yellow;
}

When you run the code in the browser, you will notice that the h1 element has a red background color—overriding the yellow background color that was set in the App.css file.

Styling With CSS Preprocessors

The third most popular way to style a Svelte component is to use a CSS preprocessor in the style tag. CSS preprocessors have a lot of advantages, they let you use advanced functions, mixins, and even support nested styling which is a feature new to native CSS.

There are many preprocessors to choose from and this includes LessCSS, Sass, Stylus, and more. To use your favorite preprocessor, you have to install it as a development dependency, by running:

npm install -D <css-preprocessor>

Or:

yarn add -D <css-preprocessor>

Make sure you replace with the name of the actual preprocessor. For example, if you want to install Less and use it in your project, you run the following:

npm install -D less

Or:

yarn add -D less

After doing that, you can add the lang attribute to the style tag and set it to "less".

<style lang="less">
</style>

And with that, you can now use all the amazing features of Less CSS in styling your svelte component.

What Makes Svelte Amazing?

Every Svelte file ends with the ".svelte" extension. The Svelte compiler parses the code written in the .svelte file and generates the appropriate JavaScript and CSS to send to the browser. This process yields faster web pages, leading to a better user experience.

If you wish to utilize an external JavaScript library in your project, you can import it directly into your .svelte file and use it without the need for a wrapper (unlike React).

ncG1vNJzZmivp6x7rq3KnqysnZ%2Bbe6S7zGiqr52cqbJuv9Oyo55lkaW9rbXCmquip56oeqm71marqGc%3D

 Share!