Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP include file.php having CSS issues

Tags:

html

css

php

I have a index PHP page where I include all PHP files like index.php?page=example. All pages are in another folder, here is the structure:

public_html/index.php
public_html/css/style.php
public_html/pages/

Index calls the CSS file from css/style.php.
Pages are called from index.php like (include pages/example.php) using GET function.

If I run index.php I get no problems with CSS, if I run only the included page like example.php I get CSS problems because the CSS is in index.php and obviously will not show the CSS correct.

But when I run the index.php and include the index.php?page=example then the index CSS show correct but the classes from the included pages does not work...

I suppose the include will only import the code but it seems like something is wrong with the server or I am doing something wrong?

Here is a example code of what I am using. This is index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
      <link rel="stylesheet" href="css/style.css"> 
  </head>
  <body>
        <?php 
        include('pages/example.php'); 
        ?>
  </body>
</html>

Index.php all css classes works fine but the style class from the included pages does not work they are just not styled

like image 494
Happy Knight Avatar asked Sep 12 '26 02:09

Happy Knight


2 Answers

You shouldn't write your css code in a php file. Better create a css file and put your style directives in there. You can include css styles best by following conventions, create a basic html template like the following and link to your css file and include the php in there.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
      <link rel="stylesheet" href="part/to/file.css"> <!-- link your stylesheet here -->
  </head>
  <body>
        <?php 
        include('path/to/file.php'); // include your php code here
        ?>
  </body>
</html>
like image 165
baao Avatar answered Sep 13 '26 16:09

baao


Make sure you have header("Content-type: text/css"); as your first line in php file so it renders correctly as css. Then do not include the file. Instead refrence to it like a normal css file only change the .css to .php. <link rel="stylesheet" href="part/to/file.php">. That should get you working. I am assuming your pulling data from a database to fill in your css, so make sure it is format correctly. Do not use something like .headertext{ color:<?=$row['headercolor'];?>; . Instead declare it in php tags. $color= $row['headercolor']; . Then in css part of php file call that variable. .headertext{ color:<?=$headercolor?>;. Hope that helps

like image 42
user3669714 Avatar answered Sep 13 '26 15:09

user3669714



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!