如何将CSS简化为几个属性


How can I reduce the CSS to a few properties

如何使用PHP减少CSS/(或)LESS?由此:

.header-logo-holder{
    display: block;
    float: none;
    text-align: center;
    margin: 10px 0;
    color: #fff;
    background: #333;
    padding-bottom: 15px;
    border-bottom: 1px solid darken(@rw-header-background-color, 10%);
    .logo{
        margin: 0;
    }
    .eg-clearfix();
}

对此:

.header-logo-holder{
    color: #fff;
    background: #333;
    border-bottom: 1px solid darken(@rw-header-background-color, 10%);
}

我只想保留规则的颜色、背景和边框。

这是我的解决方案:

<?php
//give the file (string) to the function
function keepColorBackgroundBorder($input) {
    //didn't check if the input was correct (string, not empty, etc)
    //we turn the input into an array
    $input = explode("'n", $input);
    //here is the list of strings which must be in a line to keep it in our final string
    $keep = ['{', '}', 'color', 'background', 'border'];
    $result = '';
    //foreach over the lines of the input
    foreach ($input as $key => $value) {
        //foreach over each characters we want to keep
        foreach ($keep as $key => $value2) {
            //if the characters are somewhere in the line
            if (strpos($value, $value2) !== false) {
                //we add the line + a newline character
                $result .= $value . "'n";
                //we stop the check for characters as we don't want a line to be included twice
                //e.g: border-bottom: 1px solid darken(@rw-header-background-color, 10%);
                //this example contains border and background
                break;
            }
        }
    }
    //we return the result, end delete the last newline character
    return trim($result);
}
//we get the file as a string
$input = file_get_contents('file.css');
//we call the function and we look at what was outputted
echo keepColorBackgroundBorder($input);

评论可能太多了,但总比不够好。

我使用了一个数组,这样如果你想更改的话就很容易了。例如,如果一行在开头以外的地方包含一个允许的单词,比如border-bottom: 1px solid darken(@rw-header-background-color, 10%);,它包含background,但不包含background:,那么你可以使用['background:', 'border:', 'border-bottom:']等来确保它不包括在内。

如果file.css包含:

.header-logo-holder{
    display: block;
    float: none;
    text-align: center;
    margin: 10px 0;
    color: #fff;
    background: #333;
    padding-bottom: 15px;
    border-bottom: 1px solid darken(@rw-header-background-color, 10%);
    .logo{
        margin: 0;
    }
    .eg-clearfix();
}

您将获得:

.header-logo-holder{
    color: #fff;
    background: #333;
    border-bottom: 1px solid darken(@rw-header-background-color, 10%);
    .logo{
    }
}