7

What is the best way to concatenate multiple CSS files into one CSS file?

I want to reduce the following ..

<link href="css/1.css" rel="stylesheet" type="text/css" media="all">
<link href="css/2.css" rel="stylesheet" type="text/css" media="all">
<link href="css/3.css" rel="stylesheet" type="text/css" media="all">

.. into ..

<link href="css/1-3.css" rel="stylesheet" type="text/css" media="all">

Simply doing cat css/*.css > css/1-3.css does not seem to do the trick.

5
  • Cat should work. What happens when you try it? Some rules don't work, no rules work, it can't find 1-3.css, etc?
    – user229044
    Commented Feb 3, 2010 at 14:30
  • 1
    What exactly is the problem you're getting with cat css/*.css > css/1-3.css ? Commented Feb 3, 2010 at 14:31
  • The reason your cat doesn't work as expected is maybe because it doesn't include files in the right order. Commented Feb 3, 2010 at 14:34
  • 1
    I'm sorry what is 'cat' even related to? It's not native CSS functionality...is it? Is this some CSS framework or server side solution? I'd love to know. Commented Feb 3, 2010 at 17:23
  • Byran: "cat" is a standard Unix command used to concatenate files.
    – knorv
    Commented Feb 3, 2010 at 19:13

4 Answers 4

11

As long as the ordering of the arguments for cat matches the original ordering of the three referenced CSS files in the HTML file the cat-method should work as expected.

So given say ..

<link href="css/one.css" rel="stylesheet" type="text/css" media="all">
<link href="css/two.css" rel="stylesheet" type="text/css" media="all">
<link href="css/three.css" rel="stylesheet" type="text/css" media="all">

.. the following concaternation ..

cat css/one.css css/two.css css/three.css > css/all.css

.. together will the following reference ..

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

.. should be 100 % identical.

6

At the beginning of 3.css you could add:

@import url(/css/1.css);
@import url(/css/2.css);

But i prefer using multiple link tags, or, even better, compressing my CSS into 1 file (using YUI compressor for example).

1
  • 2
    +1 YUI compressor. Also, if you can code some clever server-side stuff you can automatically minify and cat when it's requested, means you don't have to worry about it when you want to change something in the original files.
    – Ed James
    Commented Feb 3, 2010 at 14:38
1

You can also use mod_concat or a PHP solution to combine your CSS and JS files.

FYI, Robert Nyman recently wrote an article about optimizing CSS and JavaScript files.

0

You can always import your secondary CSS files from the main CSS that is included in the HTML. Here's a nice and simple tutorial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.