Search code examples
cssyii2assetsyii2-extensionyii2-module

Yii2 Assets: How to use image asset inside CSS file?


I want to create an extension which contains an AssetBundle, which provides a simple static CSS file. In that static CSS file, I want to use an image file, which is also part of the extension.

How can I know the image file's URL so I can use it inside the CSS file?

If I register the image file as an asset, it will get a random URL that we cannot predict! So it would be impossible to do something like:

.some-selector { background: url('/assets/?????/image.jpg'); }

So, how can this be done?


For further clarification, here is an example folder structure of such extension:

  • extension/Widget.php - some widget that registers our AssetBundle
  • extension/AssetBundle.php - asset bundle that registers the css
  • extension/assets/css/style.css - the css
  • extension/assets/images/image.jpg - the image we want to use inside style.css

Solution

  • In this case I would recommend to include also a new css files into the asset definition. In this case the image and css file will be in the assets folder and you can specify relative path, not absolute. e.g. /assets/a4dc56/image.jpg

    /assets/a4dc56/style.css with the following content:

    .some-selector {
        background: url('image.jpg');
    }