使用PHP文件扩展名编写动态CSS样式表效率较低吗?

使用PHP文件扩展名编写动态CSS样式表效率较低吗?

问题描述:

Ive been trying to think of ways to dynamically change a style based off of input from a website back-end (through a language like PHP). Normally I have my stylesheets be separate CSS-extension files, but these won't allow for PHP tags natively. It is, after all, extra markup in your HTML file than having all of your styles be in a separate file. Is the usage of the HTML <style> tag perhaps slower/less efficient than using a stylesheet?

我一直在想办法根据网站后端的输入动态更改样式(通过 像PHP这样的语言。 通常我的样式表是单独的CSS扩展文件,但这些文件本身不允许使用PHP标记。 毕竟,HTML文件中的额外标记比将所有样式放在单独的文件中要多。 HTML &lt; style&gt; code>标记的使用是否比使用样式表更慢/更低效? p> div>

The W3C Recommendation for CSS 2.1 contains a section on Conformance: Requirements and Recommendations, which makes no reference to filename extension but does state:

3.4 The text/css content type

CSS style sheets that exist in separate files are sent over the Internet as a sequence of bytes accompanied by encoding information. The structure of the transmission, termed a message entity, is defined by RFC 2045 and RFC 2616 (see [RFC2045] and [RFC2616]). A message entity with a content type of "text/css" represents an independent CSS document. The "text/css" content type has been registered by RFC 2318 ([RFC2318]).

Therefore, provided that the file is served with the text/css content type (and that any cacheing concerns are addressed as mentioned in @Fluffeh's answer), you should not have a problem. In PHP, the content type can be set with a call to header() before any output is sent:

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

I am not so sure that you want to do too much inside the CSS. If anything, I would suggest maybe adding some extra classes rather than doing too much dynamically. If anything, you might be better off with using PHP to pick a CSS sheet to include, but leave them as CSS. If you keep using the same file, the user can cache it, it appears much quicker. It would be better to have a stylesheet of 50k that is used ocne then cached rather than a stylesheet of 10k that is downloaded with each and every single page.