DEV Community

loading...

Create proportional columns using Flexbox in LESS

Bo Li
Updated on ・1 min read

I'm using Flexbox and LESS to create a flexible proportional column generator.

With help of Mixins I could generate a list of CSS with percentage width:

// Mixins
#mixins() {
    // Proportion Generator
    // @totalPortion: sum number of portions
    // @list: length of list is total number of columns and each number represents a concrete proportion
    // example: generator-proportion(4; 2, 1, 1) - there are 3 columns, first column has 2/4 portion and rest each has 1/4 portion
    .generator-proportion(@totalPortion; @list; @i: 1) when (@i =< length(@list)) {
        > .grid-column:nth-of-type(@{i}) {
            width: percentage(extract(@list, @i) / @totalPortion);
        }
        #mixins.generator-proportion(@totalPortion; @list; (@i + 1));
    }
}

while the less part of creating a proportioned columns is:

div.section {
    display: flex;
    flex-flow: row nowrap;
    width: 100%;

    > * {
        flex: 1 1 auto;
        word-break: break-all;
    }

    &[data-column-proportion="2:1:1"] {
        #mixin.generator-proportion(4; 2, 1, 1);
    }
}

So if there should be a new proportional section, I just need to invoke the mixin again with corresponding proportions.

But I'm wondering how could I get the @totalPortion automatically by summing up all column portions using LESS, so that I donot need to calculate the sum everytime manually and could simplify the usage?

Discussion (0)

Forem Open with the Forem app