Niet the Dark Absol
Niet the Dark Absol

Reputation: 324780

Adjust child size based on number of children

I want to make a UI that is similar to tabs in a browser.

To this end, I have elements with this CSS:

width: 20%;
max-width: 150px;

Nice and simple, responsive and awesome.

Only supports five tabs, though. If I want to support 10 tabs, it's as easy as changing to width: 10%.

So basically, I want something like:

width: calc(100% / number-of-children)

If such a thing were possible, that'd be amazing.

I'm currently just using JavaScript to set the width to the above expression. Simple, functional, but I figured I'd ask if anyone knows of a CSS-only solution.

Upvotes: 1

Views: 266

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

with CSS3 you may use display: flex. E.g.

markup

<section>
  <div>tab 1</div>
  <div>tab 2</div>
  <div>tab 3</div>
  <div>tab 4</div>
</section>

Css

section {
  display: flex;
}

div {
  flex-grow: 1;
  max-width: 150px;
}

Codepen example: http://codepen.io/anon/pen/EGbpH/

Upvotes: 3

AndrePliz
AndrePliz

Reputation: 259

In CSS3 there's a function called calc() so you can use

width: calc(100% / 10);

Here you can find documentation and which browser support it ;)

Upvotes: 1

Turnip
Turnip

Reputation: 36722

display: table is your friend.

ul {
    display: table;
    width: 100%;
}

li {
    display: table-cell;
}

Demo

Upvotes: 2

Related Questions