Laravel component class attribute not working with tailwindcss

378 views Asked by At

I am trying to pass an arbitrary class for bg image bg-[url('/img/footer-artist-pics.jpg')] for a laravel component but classes for bg-image is not added by tailwindCss JIT.

<x-section class="bg-gray-100 bg-[url('/img/footer-artist-pics.jpg')] bg-no-repeat bg-bottom bg-center">
</x-section>

The same thing works if I use a div bg-[url('/img/footer-artist-pics.jpg')]

<div class="bg-gray-100 bg-[url('/img/footer-artist-pics.jpg')] bg-no-repeat bg-bottom bg-center">
</div>

I am using a simple blade file for this component with merge attribute on class

<div {{ $attributes->merge(['class' => 'py-10']) }}>
    {{ $slot }}
</div>

webpack config

mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css').options({
    postCss: [
        require('postcss-import'),
        require('tailwindcss'),
        require('autoprefixer'),
    ],
});

Tw config

const defaultTheme = require('tailwindcss/defaultTheme');

module.exports = {
    content: [
        './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
        './storage/framework/views/*.php',
        './resources/views/**/*.blade.php',
    ],

    theme: {
        extend: {
            fontFamily: {
                sans: ['Nunito', ...defaultTheme.fontFamily.sans],
            },
        },
    },

    plugins: [require('@tailwindcss/forms')],
};

I am using Laravel 9 (Laravel Mix v6.0.43) with Tailwind 3 and scss

2

There are 2 answers

1
lordisp On

If you need to make sure Tailwind generates certain class names that don’t exist in your content files, use the safelist option

module.exports = {
    content: [
        // ...
    ],
    safelist: [
        'bg-gray-100',
        'bg-whatever-image',
    ],
    // ...
}
0
Guille On

What if you pass the url /img/footer-artist-pics.jpg as a prop to the blade component instead and then use it in the main class with binding?

Maybe something like:

$url = '/img/footer-artist-pics.jpg';

<x-section :url="$url" />

And in x-section component:

<div class="bg-[{{ url($url) }}]">
  ... many things ...
</div>