user656925
user656925

Reputation:

HTML / CSS Modules - Best Practice?

I'm starting to pull out independent pieces of HTML into their own files and include them using the PHP include keyword.

I have a CSS file about 1500 lines long. What' I'm considering doing is placing embedded CSS with the corresponding HTML files.

Of course leaving components that are used in different HTML blocks.

This way I have modular HTML / CSS blocks that I just include on the server using PHP include

Is this best practice? Yes/No, Why

Upvotes: 5

Views: 663

Answers (3)

Philipp Lenssen
Philipp Lenssen

Reputation: 9228

There are several things to consider here to see what's best for you:

  • Does your server currently send the http-gzipped version of the CSS files to make it as fast as possible?
  • Did you minify the CSS to see how small you can get it (several tools out there minify files for you, like YUI Compressor)?
  • Sending the CSS as snippets will mean the file can't be cached by the browser; check if that's worth it. It depends on a number of variables, like average pages per visitor (a look into Google Analytics or another statistics software may help), size of chunks vs overall CSS size, etc.
  • There may or may not be minimal server computation overhead for serving chunks with PHP as opposed to flat files without PHP; check if that's relevant to your situation.
  • Do you serve media-dependent CSS? If so, ensure that the chunks get served only when needed (e.g. a mobile device may only need the mobile chunks).

Upvotes: 1

Galen
Galen

Reputation: 30180

Browsers cache CSS files... because of this loading one large CSS file isn't a big deal.

If you wanted to make it super efficient, you could split the css into their different modules. Then create a "build system" that checks which modules are being used and creates one CSS file (minified even) with only the necessary CSS.

Upvotes: 3

Bojangles
Bojangles

Reputation: 101543

I wouldn't embed your CSS into the HTML file directly, but have an external stylesheet for each file. In much the same way you should keep your JS separate from your HTML, this keeps your CSS separate too. Then all you need to do to include your CSS is

<link rel="stylesheet" href="path/to/style.css">

Which you would put below any global stylesheet includes. This also keeps page-specific CSS confined to loading on only that page, so no bandwidth is wasted transferring styles you will never use.


However, if you're include()ing say, 15 files into your page, you don't want to make 15 requests for CSS files. In this case, you should group them into larger files to reduce the number of requests required.

Upvotes: 1

Related Questions