简体   繁体   中英

$variable in style=“background-image: url:( );”

I have a question for using a variable as IconPath for setting an background-image: url()

<div style="background-image: url($iconPath)"></div>

I have no idea how I can set the url for the background-image with a variable?

I tried with "" , '' , \\"

Has anyone an idea?

PHP is a server side language, so if you want anything to be visible to DOM (ie to your HTML), you will have to print it to DOM.This is achieved through echo

<div style="background-image: url('<?php echo $iconPath ?>')"></div>

Any variable value if needed to be printed, just echo it and it'll be visible to DOM.

You can echo the PHP variables to get its value in HTML. So try like this

<div style="background-image: url('<?php echo $iconPath;?>')"></div>

You could use

<div style="background-image: url(<?php echo $iconPath; ?>)"></div>

Or if it is supported (short tags)

<div style="background-image: url(<?= $iconPath; ?>)"></div>

You must echo the variable with PHP. Try like this:

<?php
 $iconPath = "/yourPath/image.jpg";
?>

<div style="background-image: url(<?php echo $iconPath; ?> )"></div>

如果您的服务器端语言是PHP,则可以使用以下代码:

<div style="background-image: url('<?php echo $iconPath?>')"></div>

假设背景图片是“ picture.jpg”,则需要输入以下php代码:

echo "<div style='background-image:url(&#039;picture.jpg&#039;)'">;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM