DEV Community

Bo Li
Bo Li

Posted on • Edited on

2

Create proportional columns using Flexbox in LESS

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?

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay