0

Alright so I was creating a normal page in html and have linked a CSS page to it. Using

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

I was wondering if I wanted to use the same method of CSS on some PHP that is echoed out onto the page. Is there a way to do this or do I have to do it using style="" within the tag?

This is what I've tried...

#test{
     width:75px;
     background-color:#FFF;
     display:inline-block;  
}

<?php
     echo '<a href="test.php" id="test">Test</a>'
?>
user2892875
  • 99
  • 1
  • 1
  • 9
  • Sure, just as long as you have `` wrapping tags. For example http://stackoverflow.com/a/19403636/ and http://en.wikipedia.org/wiki/Dynamic_Cascading_Style_Sheets - You can use inline or as an include. – Funk Forty Niner Aug 16 '14 at 01:48
  • PHP is processed on the server, so as long as you have something like `id="test"` on the element and the page it's on is linked to the style sheet, it will work fine. – ralph.m Aug 16 '14 at 03:42
  • Are you just trying to apply CSS styles to PHP generated text? If so, you need to understand how PHP works to understand why you simply just include the CSS file and style it like any other HTML element inside the echo. The PHP works before the HTML file is sent to the browser, and before CSS is applied. By the time CSS is applied, the only thing the browser sees is HTML, so it applies the styles exactly the same regardless of how the text is generated. – SGR Oct 28 '16 at 07:24

3 Answers3

0

you have to put the echo values on html element with a class/id that has a css

try :

<p class="colored"><?php echo $str ?></p>
Yaje
  • 2,753
  • 18
  • 32
0

It can be achieved liked this.

<?php echo '<link href="css/styles.css" rel="stylesheet" type="text/css" />'; ?>

or perhaps

<style>
    .style {
        width: <?php echo $myvalue; ?>;
    }

</style>
lindsay
  • 972
  • 2
  • 11
  • 21
0

From what I understand, you want to apply dynamically generated CSS styles.

For this, it is better to use style="" directly in the tag:

<a style="width: <?php echo $myValue ?>">Link</a>

If you want to use php within a CSS file, you can create a PHP file instead of your CSS file:

style.css.php

<?php 

header("Content-type: text/css");

?>

.style {
    width: <?php echo $myvalue; ?>;
}

Then you can link it from your html:

page.php

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

The MIME type of that PHP file will be text/css although the extension is .php

If you want the extension to be .css, you must .css files to the list of files to be interpreted by your server. If you are using Apache, you can enable mod_headers:

a2enmod headers
service apache2 restart

And create a .htaccess file with the following content:

<FilesMatch "\.css$">
  SetHandler application/x-httpd-php
  Header set Content-type "text/css"
</FilesMatch>

If you do this, you don't need to set the header manually in the css file.

Andrei Savin
  • 2,350
  • 4
  • 26
  • 40