Shakeel Ahmed
Shakeel Ahmed

Reputation: 1858

I want to add my class name with each element in css using php

I want to create css parse type..

Parse will add my class name with each element in CSS.

For example I've the following CSS

.class1 {font-size:10px}
.class2 {font-style:italic}
body {height:100%}
html {width:100%}

After my parser it will be like this.

.myclass .class1 {font-size:10px}
.myclass .class2 {font-style:italic}
.myclass body {height:100%}
.myclass html {width:100%}

I already created a function but it doesn't work when @media queries come in CSS with nested elements.

Can anybody provide me good CSS parsers/solutions. I already tried available CSS parsers. those are not good enough for my solution.

Upvotes: 3

Views: 180

Answers (3)

Gustaf Gunér
Gustaf Gunér

Reputation: 2267

For this, I recommend Sabberworm's PHP-CSS-Parser. I've used it myself and it's a fantastic tool. You can install it via Composer by adding the code beneath to your composer.json

{
    "require": {
        "sabberworm/php-css-parser": "*"
    }
}

After installing it, it's pretty straight forward. You can either pass in your CSS-code from a variable containing the css in a string, or by reading a file from a specific directory. In my example, I will read it from a directory.

$oCssParser = new Sabberworm\CSS\Parser(file_get_contents('style.css'));
$oCssDocument = $oCssParser->parse();

Now you're ready to go. On this parser's Github, they actually do have an example of how to prepend an id to all selectors. I'll show you how to do it with a class.

$myClass = ".myclass";
foreach($oCssDocument->getAllDeclarationBlocks() as $oBlock) {
    foreach($oBlock->getSelectors() as $oSelector) {
        $oSelector->setSelector($myClass.' '.$oSelector->getSelector());
    }
}

Now you've prepended the class. Now you want to return the final product, don't you? That's easily done by using the built-in function render(). Something like this

$oFormat = Sabberworm\CSS\OutputFormat::create()->indentWithSpaces(4)->setSpaceBetweenRules("\n");
print $oCssDocument->render($oFormat);

And of course, if you want to output it to a file, you can do that as well using file_put_contents().

Hope this helps.

Upvotes: 2

user3119231
user3119231

Reputation:

css-way:

*{
    background: #333;
}

js-way:

document.body.getElementsByTagName("*").classList.add("class");

or

document.getElementsByTagName("*").classList.add("class");

(php-way)

echo "<script>document.getElementsByTagName('*').classList.add('yourclass');</script>"

Upvotes: 0

Tony Hsieh
Tony Hsieh

Reputation: 163

Maybe you should just use http://sass-lang.com/ to your product

Upvotes: -1

Related Questions