Wasteland
Wasteland

Reputation: 5399

Setting an element's background image via CSS from a value in a PHP variable

Is there a way of using a php variable to manipulate css?

I'd like to add an image chosen by a user in a wordpress post (featured image) to the background of a specific div. I know how to mix php and html but, is there a way of doing the same with css?

I'm getting the image with:

$img = get_the_post_thumbnail_url($post_id, 'mySize');

Upvotes: 1

Views: 54

Answers (2)

brandizzi
brandizzi

Reputation: 27070

Well, you already know how to mix PHP and HTML, right? Then you just do the same, but creating a <style> element in <head>. You put your CSS in this element. Something like this:

<head>
    <style>
        div#myDivId { background-image: url("<%= $img %>"); }
    </style>
</head>

Upvotes: 1

Mihail Minkov
Mihail Minkov

Reputation: 2633

What you could do is something like this:

<head>
  <style>
    .user img { background-position: center center; background-repeat: no-repeat; background-size: cover; }
  </style>
</head>
...
<div class="user">
  <img src="images/trans.png" width="50" height="50" style="background-image:url(<?php echo $img; ?>);" />
</div>

Where trans.png is a small transparent png image.

Upvotes: 0

Related Questions