Dynamic CSS styling from fields for foreach loops and :hover

Hello! I have a site where various pages are styled using colours selected on their particular pages in the panel.

eg.
Page group

  • Page (blue, light blue)
  • Page (red, light red)
  • Page (green, light green)

I have everything working fine using inline styling for viewing the pages themselves. However on the parent page it loops through these children, displaying information about them in the first of their selected colours. I was using inline styling inside the foreach loop which works, and would be fine if I didn’t need to have a colour related :hover effect - on hover change to second selected colour.

I tried to implement something based on this post, to get the styles out of inline and into a sheet so I can declare :hover styles, but am stumped as to how to relate this to the foreach loop?

In the header I would be doing something like <?php if(isset($issue)) : ?> then the styles, but because $issue is only set in the foreach loop on the page in question <?php foreach($issues as $issue): ?> I’m not sure how to move forward?

Any help would be appreciated!

If there is just a set of fixed colors, you could use classes for that and just define those in your normal CSS file.

If the colors need to be defined in the Panel using their color values, you can use something like this:

<?php $colors = [];
<?php foreach($issues as $issue): ?>
  <?php $class = 'background-' . uniqid(); $colors[$class] = $issue; ?>
  
  <div class="<?= $class ?>">
    ...
  </div>
<?php endforeach ?>

<style>
  <?php foreach($colors as $class => $issue): ?>
    .<?= $class ?> {
      background: <?= $issue->primary_color() ?>; 
    }
    
    .<?= $class ?>:hover, .<?= $class ?>:focus {
      background: <?= $issue->secondary_color() ?>; 
    }
  <?php endforeach ?>
</style>
1 Like

Users will be uploading content and picking colours, so the second option you’ve shared is perfect, thank you.

I semi-understand how this is working, if you could explain exactly what’s happening with these three parts that would be brilliant:

$colors = []; Creating an array?

$colors[$class] = $issue; Populating array?

$colors as $class => $issue Assigning keys and values?

Yep. $colors is just initialized to an empty array.

Exactly. The keys are set to the unique classes, the values are the issue pages.

Kind of. It’s a foreach loop that extracts the keys of the array into the $class variable and the values into the $issue variable. You can name those differently, they don’t need to have the same names as above.

Thanks so much for your explanation and help :relaxed: