luizbills / css-generator
Write CSS programatically using PHP.
Installs: 21 229
Dependents: 0
Suggesters: 0
Security: 0
Stars: 19
Watchers: 4
Forks: 1
Open Issues: 1
Requires
- php: >=7.4.0
- ext-mbstring: *
Requires (Dev)
- codeception/codeception: ^4.2
- codeception/module-asserts: ^1.0.0
- phpstan/phpstan: ^1.8
- phpstan/phpstan-strict-rules: ^1.4
README
Write CSS programatically using PHP.
Install
composer require luizbills/css-generator
Usage
Create a generator
require_once 'vendor/autoload.php'; use luizbills\CSS_Generator\Generator as CSS_Generator; $options = [ // default values // 'indent_style' => 'space', // you can change to 'tab' // 'indent_size' => 4 // 4 spaces by default ]; $css = new CSS_Generator( $options ); // define your css code (see below) // output the generated code echo "<style>" . $css->get_output() . "</style>";
Add rules
$css->add_rule( 'a', [ 'color' => 'red' ] ); $css->add_rule( [ 'p', 'div' ], [ 'margin' => '13px', 'padding' => '9px' ] );
Output:
a { color: red; } p, div { margin: 13px; padding: 9px; }
Add global variables
$css->root_variable( 'color1', 'red' ); $css->add_rule( 'a', [ 'color' => 'var(--color3)' ] ); $css->root_variable( 'color2', 'green' ); $css->root_variable( 'color3', 'blue' );
Output:
:root { --color1: red; --color2: green; --color3: blue; } a { color: var(--color3); }
Note: all variables declared by root_variable
will be placed at the beginning.
Add comments
$css->add_comment( 'Lorem ipsum...' )
Output:
/* Lorem ipsum... */
Open and close blocks
$css->open_block( 'media', 'screen and (min-width: 30em)' ); $css->add_rule( 'a', [ 'color' => 'red' ] ); $css->close_block(); // close the last opened block
Output:
@media screen and (min-width: 30em) { a { color: red; } }
Escape selectors
Sometimes you need to escape your selectors.
<!-- Examples --> <div id='@'></div> <div class='3dots'></div> <div class='red:hover'></div>
$css->add_rule( '#' . $css->esc( '@' ), [ 'animation' => 'shake 1s' ] ); $css->add_rule( '.' . $css->esc( '3dots' ) . '::after', [ 'content' => '"..."' ] ); $css->add_rule( '.' . $css->esc( 'red:hover' ) . ':hover', [ 'color' => 'red' ] );
Output:
#\@ { animation: shake 1s; } .\33 dots::after { content: "..."; } .red\:hover:hover { color: red; }
Include anything (be careful)
$css->add_raw( 'a{color:red}' );
Output:
a{color:red}
Minify your CSS
echo $css->get_output( true ); // returns the compressed code echo $css->get_output( false ); // returns the pretty code
License
MIT License © 2022 Luiz Bills