Complex mixin for CSS grid

2019-05-28 19:00发布

问题:

I'm working on creating a complex mixin for using CSS grid. At the moment what I have is a mixin that you pass in the no of cols, row-gap and column-gap and it returns you a blob - code is below.

NB rem() is a function I'm using to convert px to rem.

@mixin grid($grid-type, $no-of-cols, $row-gap, $columnn-gap: $row-gap) {
  @supports (display: grid) {
    display: grid;
    #{$grid-type}: repeat($no-of-cols, auto);
    grid-gap: rem($row-gap) rem($column-gap);
  }
}

This works fine but the problem is if I want a more complex grid, for example, if I want to use the fr values in, how would I go about achieving this? I guess I can't really use the same mixin I've got above because that will just split the grid into equal parts as I'm using repeat($no-of-cols auto).

I'd ideally like to do something like the following:

@mixin grid($no-of-cols$, $fractions) {
  @supports (display: grid) {
    //Here I want to take the number of $fractions and output something like
    grid-template-columns:1fr 1fr 2fr //if someone had passed in (3, 1, 1, 2)
  }
}

So I guess really I'm trying to answer 2 questions;

1) Can I have one mixin/function that outputs both a grid in fractions (1fr 2fr) & numbers (using repeat(3, auto) 2) Am I making this overly complex and should this really be a function/mixin or even 2 mixins?

============================

UPDATE: So I've updated the initial Sass function so it's usage is now as follows:

@include('grid-template-columns/rows', 5px, 5px)

I've also set $row-gap to $column-gap since if this parameter is left out in pure CSS the browser will just set grid-column-gap to be equal to grid-row-gap when using the grid-gap shorthand. In case anyone needs this in future!

回答1:

Ok so in case anyone needs to use this in the future, this is what I came up with. While it serves its purpose and works it's not exactly what I had in mind. I think maybe as I originally said, I was trying to over-engineer what I was doing, which is now no longer necessary!

Sass

@mixin grid($grid-type, $args, $row-gap, $column-gap: $row-gap) {
  @supports (display: grid) {
    display: grid;
    #{$grid-type}: #{$args};
    grid-gap: rem($row-gap) rem($column-gap);
  }
}

Explanation

So you can see from the above, I'm using $args which lets you pass a number of parameters. So as I was trying to create a scenario where someone could create a layout using both fractions (fr) and equal boxes using (repeat([num], auto), this method allows me to pass in both of these.

Example usage is as follows:

@include grid('grid-template-rows', '1fr 2fr', 10px, 20px);

@include grid('grid-template-columns, 'repeat(3, auto)', 10px, 15px);

As you can see this gives the flexibility to create a grid using both rows and columns so I'd say this works for my scenario. Hope this helps someone in future and it's certainly worked for me.