Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make children auto fit parent's width only with CSS?

I have a server-side component that generates a fluid layout "toolbar" using DIV without fixed width, generating many A inside it.

Then I need customize that layout to make all A tags auto fit to the parent width. But the number of children is variable and the parent's width isn't known (it auto fits itself to the window).

I made some tests with this Fiddle: http://jsfiddle.net/ErickPetru/6nSEj/1/

But I can't find a way to make it dynamic (uncomment the last A tag to see how it ins't working, lol).

I can't change the server-side sources to gerenate HTML with fixed width. And I really would like to solve it only with CSS if there is any way, even that with JavaScript I could achieve that result.

How can I make all the children auto-fit itself to the parent's width independently of the number of children?

like image 952
Erick Petrucelli Avatar asked May 02 '11 14:05

Erick Petrucelli


2 Answers

You can use display: table-cell:

See: http://jsfiddle.net/6nSEj/12/ (or with 5 children)

This won't work in IE7 because that browser simply doesn't support display: table and friends.

div.parent {
    ..
    width: 100%;
    display: table;
    table-layout: fixed;
}
div.parent a {
    ..
    display: table-cell;
}
like image 60
thirtydot Avatar answered Sep 21 '22 12:09

thirtydot


This is already a pretty old question. Although the answers given attended well at the time, nowadays the Flexible Box Layout offers the same result with much more simplicity, with good support in all modern browsers. I strongly recommend it!

/* Important parts */
.parent {
  display: flex;
}

.parent a {
  flex: 1;
}

/* Decoration */
.parent {
  padding: 8px;
  border: 1px solid #ccc;
  background: #ededed;
}

.parent a {
  line-height: 26px;
  text-align: center;
  text-decoration: none;
  border: 1px solid #ccc;
  background: #dbdbdb;
  color: #111;
}
<div class="parent">
  <a href="#">Some</a>
  <a href="#">Other</a>
  <a href="#">Any</a>
</div>

<br>

<div class="parent">
  <a href="#">Some</a>
  <a href="#">Other</a>
  <a href="#">Any</a>
  <a href="#">One More</a>
  <a href="#">Last</a>
</div>
like image 41
Erick Petrucelli Avatar answered Sep 22 '22 12:09

Erick Petrucelli