There's a way to set a default directory for the images used in css?
I have a css file which, for organizational sake, is in another directory from the one where the images are. The thing is I always end up setting all the background-images like this: background-image: url(../img/Untitled.jpg)
.
There's anything lik开发者_如何学编程e the HTML's <base>
tag that can be used in css so I don't need to put that "../img/
" to every single background-image
?
Another possible option would be to create your css styles using php or another server side language. You can then use a directory variable to spit out the full path for each item.
styles.php
<?php
header("Content-Type: text/css");
$imageDir='../images';
// or
// $imageDir='/newsletter/2010/jan/17/business/category/7/img';
?>
.divClass{
background : url('<?php echo $imageDir; ?>/kitten.jpg');
}
No, I'm afraid you are stuck with that syntax.
EDIT: You might want to check out http://lesscss.org/. With variables you could at least define all of the urls at the top.
URL rewriting is your friend here.
CSS image references are always relative to the URL of the CSS file. Let's assume that our CSS files live inside the /css
and that we want our image resources to live inside /img
and that we're tired of having to put ../img/
in front of every image reference.
All relative CSS image references are relative with respect to the URL of the css file containing the reference. Set up URL rewrite rules to rewrite urls like these
/css/foobar.png
/css/blue-theme/header-background.png
so they are relative to the desired location (/img
):
/img/foobar.png
/img/blue-theme/header-background.png
Et voila! Problem solved.
You can do this sort of this with Apache's mod_rewrite. Should be about as simple as adding the following to the appropriate .htaccess
.
Options +FollowSymlinks
RewriteEngine On
RewriteRule ^css/(([^/]+/)*)([^/\.]+\.(gif|jpg|jpeg|png))$ img/$1$3
More difficult on IIS, but the notion remains the same.
There is not really a solution to that unless the css is in the same directory as the images.
but as you say in the question that is not the case, so the only way to show where the images are is give the relative location for each background-image
or the static image (with the http://...
)
One thing you can do is rather than going up and over with relative paths, you can always come down from the domain root. This URL would look more like url(/img/Untitled.jpg)
and it would be the same in all CSS files regardless of how deeply nested they are underneath the domain.
精彩评论