I need to insert PHP code into a stylesheet

In my css

div.image { width:<?php echo get_image_size( $size[1] ); ?>px; } 

The size is stored in the array, so I called $ size [1] here ...

I am starting in php ...

help of any pl?

+6
source share
6 answers

For this you need to use like this

  • change your css file as css.php, and use a stylesheet for example

    <link rel="stylesheet" type="text/css" href="css.php?opt1=<?php echo get_image_size($size[1] ); ?>" />

  • In css.php file

    div.image { width:<?php echo $_GET['opt1']; ?>px; }

try it

+1
source

The best solution is to set the header for the css / php file in my cssfile.php example:

 <?php header("Content-type: text/css"); ?> 

Then you can use the php file as a style.

 <link rel="stylesheet" type="text/css" href="cssfile.php?param=1" /> 

Then you should get the result on your website. But with this solution you have to be very careful if you have a lot of traffic. On each site, you can use your PHP interpreter to deliver this file.

+8
source

Yes, for this particular instance, if you just need php on this one line, it’s better to insert html into your head instead of php creating the entire css file for you.

 <style type="text/css"> div.image { width:<?php echo get_image_size( $size[1] ); ?>px; } </style> 

PHP should not create your static assets unless absolutely necessary. You will notice that performance drops if traffic gets high.

+4
source

Change the extension to .php and then in the stylesheet:

 <?php header("Content-type: text/css"); ?> 

Then you can use PHP inside your stylesheet.

+3
source

Perhaps you should use this:

 <div class="image"> <img src="image.gif" /> </div> 

CSS

 div.image img{ width: 100% } 

The problem with putting style inside html is that everything becomes messy. You should try to separate html from css and js as much as possible.

Also, from my point of view, it is not a good practice to use php in css or js files.

Consider viewing your html layout to optimize it.

+3
source

One way is to move this part from the .css file and paste it into a PHP document that has access to the get_image_size () function. For example, you might have a template that is parsed as a title. You can then place this snippet in the <style> tags.

+1
source

Source: https://habr.com/ru/post/914225/


All Articles