Dan Dinu
Dan Dinu

Reputation: 33368

How to deal with paths in CSS when including the same css file from multiple directories

I have the following folder structure

website 
    \styles\ 
         main.css
    \directory\
         page.php  
    \layout\ 
         background.jpg 
         common_includes.php 
    index.php 

main.css contains background-image such as

 #container  {
    background-image: url('../layout/background.jpg'); 
 }

common_includes.php contains CSS and JS files which are common to all pages.Eg:

 <link rel="stylesheet" type="text/css" href="styles/main.css" />
 <link rel="stylesheet" type="text/css" href="styles/other.css" />
 ... 

index.php

  <?php include_once '/layout/common_includes.php'; ?>

Everything perfect until here.

Now I want to have a folder with other pages (/directory/page.php).

I want page.php to use the same common_includes.php.

Obviously by doing:

  <?php include_once '../layout/common_includes.php'; ?>

doesn't work due to a different Working Directory.

I tried duplicating common_includes.php to have correct paths:

common_includes_directory.php

<link rel="stylesheet" type="text/css" href="../styles/main.css" />
<link rel="stylesheet" type="text/css" href="../styles/other.css" />
...

THen I got into the problem that the background.jpg in the CSS cannot be found.

How can I achieve this without having to duplicate everything?

Upvotes: 1

Views: 331

Answers (1)

Rehan Haider
Rehan Haider

Reputation: 1061

Use absolute path(relative to root)

<link rel="stylesheet" type="text/css" href="/styles/main.css" />
<link rel="stylesheet" type="text/css" href="/styles/other.css" />

In css use

#container  {
    background-image: url('/layout/background.jpg'); 
 }

Any path which starts with "/" is relative to root and it remains same wherever you use it. For more details read Having links relative to root?

Upvotes: 1

Related Questions