Dynamic Css background URL

Asked

Viewed 376 times

0

To change a property html dynamically by php, I use a code similar to that :

<img src="<?php echo $foo;?>"/>

You can change the Url of background in css by php

example:

.foo{background:url('foo.jpg');}
  • Can change via style=, inline, or create a <style>, or create a x-background, for example, and manipulate via JS. I think it’s the only option.

2 answers

2


You can create a PHP page to generate dynamic CSS according to your need as follows:

  1. Create the.php style page
  2. Put the header the same for css header("Content-type: text/css")

Example:

<?php
    header("Content-type: text/css");
?>
.foo{
    <?php
        //condições aqui
    ?>
}

And on your page you can call the file with the link equal to a normal css

<link rel="stylesheet" type="text/css" href="estilo.php" />

If you want to change the CSS of an element directly in HTML, you can use CSS inline with PHP, for example:

<div class="foo" style="background-image:<?php echo $foo; ?>;"></div>

In this way even in the CSS document foo have some background-image, the same will be disregarded and the inline will be interpreted in its place.

You can also directly change the tag src or put a style in the element you want to handle with JS, example:

$('#seu-elemento').attr("src", "caminho-para-nova-imagem");

Or manipulate the properties css of the same

$('#seu-elemento').css({"background-image" : "caminho-para-nova-imagem"});

0

Only if your CSS is generated in the file (phtml) in the . css file it does not process PHP and cannot do this.

It is possible to do it via javascript.

  • it is possible to make the css interpret the php, or rather make the file php a stylesheet ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.