2

Consider this CSS Property:

background: url(http://images.something.com/background.png) left top repeat-x;

Is there a way to dynamically specify the URL being used in the external file (Meaning the URL is sort of automatically generated rather than hard-coded in the CSS file) ?

Thanks.

2
  • Do you want your host to be dynamic (in your case http://images.something.com/) or the image name? IMO, I dont think the image name can be dynamic Commented Jun 17, 2010 at 7:28
  • Well yeah, how can I do that? Commented Jun 18, 2010 at 2:33

4 Answers 4

3

Dynamic CSS Background URLs

There is another cool trick.

You could add a

.php

to the file's name so it will be Hypertext Preprocessed next time, someone calls it.

Now you can easily do (in your CSS file):

<?php $num = rand(1, 3); ?>

background: url(http://images.something.com/background<?php echo $num; ?>.png) left top repeat-x;

This will switch randomly the background-image between

background1.png, background2.png and background3.png

P.S. Dont forget to update your <link> to your css.php file.

Sign up to request clarification or add additional context in comments.

Comments

2

background: url(http://images.something.com/getimage.html?image=random) left top repeat-x;

And in the getimage.html, check if request[image] == "random". Using whatever server-side language you desire, respond with an arbitrarily or randomly selected image.

4 Comments

It'd probably get getimage.php but, whatever :P Your logic is right.
This works if you're setting a random (in this example), but if you want an image that's produced based on the context of the page? Your options there are pretty much limited to some manner of scripting language (either client- or server-side) to load a more specific image.
@Mark: Yeah, I know. I figured I'd make it language agnostic though. It could also be getimage.aspx or something else.
Thanks for the answer but it's not what I'm looking for. What I want is to dynamically specify the URL itself so I won't be bothered changing URLs in the css file every time I work locally or when I will transfer to another domain. Am I making sense here? Thanks.
0

Yes.

You can call a server-side page, and based on variables, it can put in different CSS there.

If you just mean with html/css -- there is very little you can do dynamically.

Comments

0

You can also set background images using Javascript (there are a large quantity of possibilities), but HTML and CSS are, by nature, static languages.

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.