1

I'm using wordpress and ACF plugins to add an image :

http://www.advancedcustomfields.com/resources/image/

I would like to add an image in a div as a background. I used this code in my style.css but it doesn't work :

background-image: url(<?php $image = get_field('image_projet');?> <img 

src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />);

Thanks for you help

Popy Sunny
  • 43
  • 1
  • 4
  • you're adding html to the css file. – Billy Feb 21 '16 at 10:25
  • You cannot use PHP code inside a CSS file, you can do it within an inline css code(style tags), which is still not a best practice,..can you please elaborate your question a bit more, the code snippet is not very clear – Vishnu Nair Feb 21 '16 at 10:29
  • is not recognized inside the double quotation – Pooya Feb 21 '16 at 10:39
  • What do you try to tell us with the code fragment given? Is this supposed to be a CSS file? HTML? PHP? Why do you mix CSS with html? You're not echoing anything in the CSS part. – m02ph3u5 Feb 21 '16 at 11:07

2 Answers2

1

A css file contains CSS. Just CSS. You can't write html or PHP into a CSS file. If you want to generate a CSS property with PHP, you must use the <style>...</style> tags directly in your PHP file (the view). For instance :

<?php $image = get_field('image_projet'); // fetch the ACF field ?>

<html>
    <head>
        <title>Page's Title</title>
        <style>
            .your-div {
                background-image: url('<?php echo $image; ?>');
            }
        </style>
    </head>
    <body>
        <!-- this div uses the $image URL as a background. -->
        <div class="your-div">
            Lorem Ipsum.
        </div>
    </body>
</html>
Stéphane
  • 116
  • 6
  • Ok, the image in background works, but i have the same images for all articles ! Each article have one unique image. I tried this code : background-image: url(''); but it doesn't work. I need the "$image['alt']; " – Popy Sunny Feb 21 '16 at 10:55
0

do it this way , you can't add alt via css so use title instead, look here, SO css background image alt attribute

`<div style="background-image: url( <?php echo $image['url']; ?>); height: 200px; width: 400px; border: 1px solid black;" title= "<?php echo $image['alt']; ?>">my DIV  with a background image:</div>
Community
  • 1
  • 1
Billy
  • 2,448
  • 1
  • 10
  • 13