Background Image Inline CSS URL

Hi There!

I got into Kirby recently and I’m in love with it’s simplicity and thorough documentation.
However, I have a little problem: I wan’t to pull the background image from a field and place it in an inline css style. I did it like that:

<div class="test" style="background-image: url(<?php echo $page->background()->url()?>) no-repeat">Test</div>

Unfortunately the background is not shown, and oddly the rendered URL seems to miss some directories, it renders:

/main/background-image.jpg

instead of:
main/content/home/background-image.jpg

I know similar questions have been answered but it didn’t work for me.
What am I doing wrong?

Best, Felix

You need to put it through toFile() first:

<div class="test" style="background-image: url(<?= $page->background()->toFile()->url()?>) no-repeat">Test</div>

You should also check the image physically exists first, or you will get an error…

<?php if($bgimage = $page->background()->toFile()): ?>
    <div class="test" style="background-image: url(<?= $bgimage->url()?>) no-repeat">Test</div>
<?php endif ?>
1 Like

Cool, this solved my issue! Thanks for the quick reply!