Background images in TailwindCSS - the clean and easy way

pavelloz

Paweł Kowalski

Posted on October 14, 2021

Background images in TailwindCSS - the clean and easy way

My biggest issue with TailwindCSS was the ugly way of using background images with it. I had to inline background-url property and it was not clean. And I know I was not alone, because other frontend developers said the same thing. It looked similar to this:

<section class="bg-accent-dark bg-cover"
  style="background-image: url({{ 'images/home/hero.jpg' | asset_url }})">
Enter fullscreen mode Exit fullscreen mode

Note: We use liquid to generate url to an image placed on CDN.

Couple days ago, when I was doing six different themes in TailwindCSS using six different configs (I will report my findings in another article) I discovered that it can be simplified. Because CSS file is also on CDN, and the background-image can be customized in TailwindCSS config (read more), it can be replaced with simple bg-hero after adding its definition into theme extend section:

backgroundImage: {
  'hero': "url('../images/home/hero.jpg')"
}
Enter fullscreen mode Exit fullscreen mode

Now, our hero element HTML looks like this:

<section class="bg-accent-dark bg-cover bg-hero">
Enter fullscreen mode Exit fullscreen mode

And I think its much cleaner! Reading documentation paid off :)

Read more

If you are interested in more performance oriented content, follow me and I promise to deliver original, or at least effective methods of improving your website.

💖 💪 🙅 🚩
pavelloz
Paweł Kowalski

Posted on October 14, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related