Select a value:


Description:

This experiment was the result of wanting to change CSS values based on data-attributes of an HTML element.

The main element of this page looks like this:

<main id="main" data-switch="1"></main>

When you change the value of the select list, some javascript code is triggered which changes the value of the "data-switch" attribute of the <main> element.

There are some CSS styles which look like this:

As the data-switch attribute changes value, the corresponding CSS is called to style the main element. This is a simple example using different colors. But, it could also apply to more complex CSS layouts using grid or flexbox containers. Data attributes could pass values for the numbers of columns or rows to change the layout of the user interface. Or, it could be used to pass height or width values to change the size of elements. The example below demonstrates how data attributes can be used to modify the layout of a CSS grid. The select list allows you to choose the number of columns, which updates the `data-columns` attribute of the grid container. The CSS then uses this attribute to set the appropriate `grid-template-columns` property, changing the layout of the grid.


Select number of columns:

1
2
3
4


You can download this code and play around with it here: experiment3.zip