Is there any way to create a conditional statement with variables in CSS?

78 Views Asked by At

"I'm attempting to create a gallery where clients can choose the number of columns. I've implemented a range selector in my admin panel, allowing clients to choose between 1 and 6 columns. I've passed this setting to HTML to adjust the variable in Twig, specifically --gallery-columns.

<section class="gallery" style="--gallery-columns: {{ gallery_columns }}">

in CSS:

.gallery-container {
  display: flex;
  flex-wrap: wrap;
  gap: var(--gutter-w);

  > img,
  > video {
    object-fit: cover;
    width: calc((100% - (var(--gallery-columns) - 1) * var(--gutter-w)) / var(--gallery-columns));
    height: 100%;
  }
}

While it functions well on desktop, I'm encountering issues with responsiveness. I aim for the gallery to maintain the same proportions on all devices. For example: if there are 6 columns on desktop, I'd like 3 columns on mobile; if there are 4 columns on desktop, I'd prefer 2 columns on mobile, and so on.

Is there a way to achieve this using only CSS, or what are my options for handling this?

The following code is obviously not working. Is there something similar that exists, or are there alternative approaches?

@media (--gallery-columns: 1) {
  // styles if --gallery-columns equal 1
}

@media (--gallery-columns: 3) {
  // styles if --gallery-columns equal 3
}
0

There are 0 best solutions below