Adding CSS variables to apply to a particular module instance

by William   Last Updated July 05, 2019 18:10 PM - source

I have a module that has to display a variable number of rows, based on how the user configures it in the back-end, and several instances of the module need to be displayed on the same page (with potentially different numbers of rows). The main challenge is styling it so the rows appear at the bottom of the div rather than the top. My current approach is to pass the number of rows to my CSS in the form of a CSS variable, as well as the padding. This is roughly what my code looks like:

$document = JFactory::getDocument();
$modulePath = JURI::base() . 'modules/mod_my_module/';
$rows_array = $params->get("rows");
$number_of_divs = count($rows_array);
$padding = 100 - (10 * $number_of_divs);
$style = ":root { --rowNum: " . $number_of_divs . "; --padding: " . $padding . "%;}";

Then in my CSS I'm using these variables in a grid layout, like

display: grid;
grid-template-rows: var(--padding) repeat(var(--rowNum), 10%); 

When I have a single instance of my module this works fine, but if I have several instances rendered in the same page then these variable declarations collide and it doesn't work anymore. I think the issue is that $document->addStyleDeclaration($style); is applying the style rule to a global style-sheet, but I need to do something that only effects the style of the particular instance.

How can I style the different instances of the module with different numbers of rows? Should I be dynamically adding the rows using Javascript instead?

Related Questions

Joomla: How to make a table view in module-backend?

Updated January 22, 2018 06:10 AM