Search code examples
csscompass-sasssass

Division of percentage dependent on number of columns


I'm styling up a bar chart. There are potentially unlimited bars and I need them each to have a proportional width to their parent container- currently I have something like:

.one-column  {
    width: (100% / 1);
}

.two-columns {
    width: (100% / 2);
}

.three-columns {
    width: (100% / 3);
}

etc

... which I would add to each bar.

Can anyone think of a clever way of getting around this and just having one rule that could handle unlimited columns - maybe something to do with data attribute?


Solution

  • With some tricky combinations of CSS3 selectors you could find out how many columns are in use and dependent on that style the width of the containers:

    div:first-child:last-child {
    width: 100%;
    }
    div:first-child:nth-last-child(2), div:last-child:nth-first-child(2) {
    width: 50%;
    }
    div:first-child:nth-last-child(3), div:first-child:nth-last-child(3) ~ div {
    width: 33.33%;
    }
    div:first-child:nth-last-child(4), div:first-child:nth-last-child(4) ~ div {
    width: 25%;
    }
    

    As you can see, you will still need to add a rule for every possible number of divs, but you don't need to detect anymore how many divs are there and to set classes accordingly.

    But there is also another possible solution in your case. You could use display: table, display: table-cell etc. on the divs and the parent element in an appropriate way. Then if you set the width of the parent to 100% and the width of the containers to all the same value (e.g. 1%), you will get exactly what you wanted to.