variable to css

jonaweb posted 3 years ago

Is it possible to pass a variable to the css-file?
Something like
Background-color: #{{{ $item->variable }}};
to give each single product an own backgroun-color
How can this be done?

pogachar replied 3 years ago

One way would be inline styles or styles in <head>. I don't think you can use variables in .css file

Garbee replied 3 years ago

You'd need to run the CSS files through PHP for something like:

<?= $item->variable ?>

to work. You won't get blade structures in there like your example. However, this is not recommended. What you should do is instead use Sass to generate multiple static stylesheets, then use a session setting to send the right one with the view. At least until CSS variables are in more browsers and you can start using those client-side with JS to manipulate it on-the-fly.

Ehesp replied 3 years ago Solution

One way of doing it would be to have a default background color set in your css file, then in your view page just do:

// foreach product { 

   <div class="product" style="background-color: {{ $product->color }}">

// }
GuruQuest replied 1 year ago

Yes as per new update in CSS version and Browser flexibility. The developer can create a variable in CSS.

As per reference of create variable in CSS file we can make it happen.

It can be done with two steps:

  • Declare variable in root
  • Use that variable in code
:root  {
     --border-color: #e8e8e8;

Now, we create --border-color variable that we have to apply in div tag.

div { 
     border: 2px solid var(--border-color);
davidtoledo replied 5 months ago

@GuruQuest That was awesome! Tks!

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us