Homepage

Adding Visuals to Pages: CSS

Last edit: Jun 06, 2024

This guide will help you add visuals (images) to your pages using a CSS file, and accessing and displaying the image through its relative path.

Requirements

To follow the steps in this tutorial, you should be familiar with the required directory structure for your codebase, and understand the concepts of pages, layouts, and assets.

Steps

Adding visuals to your pages using a CSS file is a three-step process:

Step 1: Create styles and images directories

If you are starting from scratch (without having created the codebase), create an assets directory inside app, then a styles and an images directory inside assets.

If you have already created the codebase, you can skip this step, and just locate your app/assets/styles and app/assets/images directories.

Put an image in the images directory (e.g. logo.svg).

Step 2: Create CSS file

In the styles directory, create a page.css file:

.logo {
  background: transparent url("../images/logo.svg") top center no-repeat;
}

Here, in a static CSS file, you can't use the asset_url filter or {{ asset_url }} liquid variable to get the URL of the image on the CDN, so you have to refer to it with its relative path.

On your computer, the CSS file is in the app/assets/styles directory, so to point to the image file in the app/assets/images directory, you have to go one level up from styles (..) to the assets directory, and then write the path relative to there.

This directory structure corresponds to the directory structure on the CDN, so the relative path works the same way on your Instance.


<link rel="stylesheet" href="{{ 'styles/page.css' | asset_url }}">

Sync or deploy. The image is displayed on your page.

Next steps

Congratulations! You have learned how to add an image to your pages using CSS. You can also learn about adding visuals to your pages in Javascript.

Questions?

We are always happy to help with any questions you may have.

contact us