Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge and clean 2 css files with overlapping selectors/properties?

Tags:

html

css

Here I am, trying to do a decent job at maintaining a site and adding new elements to it. But before that, I'd like to clean its css files.

That site is using 2 stylesheets, a v1 and a v2. Basically, the v2 adds new rules but also overrides rules/properties from the v1. So I can't just get rid of v1 because v2 doesn't contain all rules and properties.

Here's a quick example

From v1

.globalFooter {
    background-color: #eee;
    color: #fff;
    font-size: 15px;
}

From v2

.globalFooter {
    font-size: 18px
    display: inline
}

And so, the result should be like

.globalFooter {
    background-color: #eee;
    color: #fff;
    font-size: 18px;
    display: inline
}

I thought about manually merging v2 into v1, moving the new elements and overriding properties, but v2 is 3000 lines long...

So then I tried to find a tool that would do that automatically but I didn't find anything solid. I need something that can merge the two files and consider that the 2nd file is loaded after, so it can overrides rules and properties of the 1st one.

Does someone know a good tool/script doing that ?

Thanks

like image 212
Link14 Avatar asked Aug 05 '16 23:08

Link14


People also ask

Can I use 2 CSS files?

Yes, It is possible to include one CSS file in another and it can be done multiple times. Also, import multiple CSS files in the main HTML file or in the main CSS file.


2 Answers

There is This and This list of other helpful tools

like image 186
Luka Kerr Avatar answered Sep 27 '22 15:09

Luka Kerr


With this combination i solved and optimize the css to the maximum.

After configuring Grunt, install the following plugins:

  • grunt-postcss
  • grunt-contrib-cssmin
  • grunt-cssnano
  • clean-css
  • postcss-flexbugs-fixes
  • autoprefixer

Gruntfile.js

Create the task to minify, merge selectors & properties, remove duplicates, etc.

cssmin: {
    options: {
        advanced: true, 
        mergeAdjacent: true,
        removeDuplicates: true,
        shorthandCompacting: false 
    },
    files: {    
        src: 'your/path/style.css',
        dest: 'your/path/style.min.css' 
    }  
},

After create a task to parse CSS, add prefixes and optimize more.

postcss: {
    options: {
        processors: [
            require('postcss-flexbugs-fixes'),
            require('autoprefixer')({
                browsers: [  
                    'last 2 versions',  
                    'Edge >= 12',
                    'Explorer >= 9']
            }),
            require('cssnano')
        ],
        map: false,
    }, 
    files: {    
        src: 'your/path/style.min.css',
        dest: 'your/path/style.min.css' 
    }
}

Register a shortcut to the tasks

grunt.registerTask('css', ['cssmin', 'postcss']);

And Voilà!!

grunt css 
like image 24
Tiago Fontella Avatar answered Sep 27 '22 15:09

Tiago Fontella