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

4
  • you're adding html to the css file. Commented Feb 21, 2016 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 Commented Feb 21, 2016 at 10:29
  • <? is not recognized inside the double quotation Commented Feb 21, 2016 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. Commented Feb 21, 2016 at 11:07

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

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('<?php echo $image['url']; echo $image['alt']; ?>'); but it doesn't work. I need the "$image['alt']; "
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.