Home > Article > Web Front-end > How Can I Implement Conditional Styling in CSS Without Using if/else Statements?
<p><p>In your CSS:
p.normal { background-position: 150px 8px; } p.active { background-position: 4px 8px; }<p>CSS Preprocessors:<p>Use preprocessors like Sass to introduce conditional statements:
$type: monster; p { @if $type == ocean { color: blue; } @else if $type == matador { color: red; } @else if $type == monster { color: green; } @else { color: black; } }<p>Note that preprocessors require preprocessing, and conditions are evaluated at compile time.<p>Custom Properties:<p>Leverage custom CSS properties (CSS variables) for run-time evaluation:
:root { --main-bg-color: brown; } .one { background-color: var(--main-bg-color); } .two { background-color: black; }<p>Server-Side Preprocessing:<p>Preprocess your stylesheet using a server-side language such as PHP:
p { background-position: <?php echo (@$_GET['foo'] == 'bar')? "150" : "4"; ?>px 8px; }<p>Other Techniques: <p>Refer to Ahmad Shadeed's article for advanced CSS techniques to address conditional styling without if/else.
The above is the detailed content of How Can I Implement Conditional Styling in CSS Without Using if/else Statements?. For more information, please follow other related articles on the PHP Chinese website!