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 blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More