Search code examples
cssflexboxcss-variables

Using CSS custom properties with flexbox


I want to use CSS custom properties within a flexbox to define my flex-basis, which can be variable. The following code doesn't work correctly. The variable is computed fine but the flex-basis just isn't applied. Is it possible to use custom properties within the flex property like this?

.row-flex {
    --flex-basis: 30%;

    display: flex;
}

.row-flex >:first-child {
     flex-basis: 0 0 var(--flex-basis);
}

Solution

  • custom properties is working fine with flexbox but the problem is with your last css line.

    you should use as:

    .row-flex >:first-child {
         flex: 0 0 var(--flex-basis);
    }
    

    or

    .row-flex >:first-child {
         flex-basis: var(--flex-basis);
    }
    

    flex-basis takes only one argument which is the value. while flex takes 3 args: (flex-grow - flex-shrink - flex-basis)

    see this example