tags:

views:

68

answers:

4

This is what I am trying to do :

HTML

<div class="container">
    <div id="one" class="child">One</div>
    <div id="two" class="child">Two</div>
    <div id="three" class="child">Three</div>
    <div id="four" class="child">Four</div>
</div>

CSS

<style type="text/css">
     .container{
        height:40px;
        width:500px;
     }
     .class{
        float:left;
        /*...*/
     }
</style>

The child divs should fill the container div how big or small it has its width. They can get big according to the container automatically.

|<---One----><---Two---><-Three-><--Four-->|

How can I do it with css?

Thanks in advance.

+2  A: 

You can set the .child width to 25%, like this:

.child { width 25%; }

You can test it out/play with it here.

Nick Craver
+1 for providing an example. As you always do :)
Marko
+2  A: 

I've set up a test site to make sure this works:

First, you'll need to keep float to "left" to keep everything on the same row. Next, set width to "25%", to space out the elements. Finally, set text-align to "center" to center the elements, as in your diagram. Remember, if you change the number of elements, you'll need to modify the "25%" to a value that evenly spaces out the elements. (Use 100 / numElements).

.child {
  float: left;
  width: 25%;
  text-align: center;
}

Does anyone know a way to do this without using width percentages, so that it will auto-spread the elements if they are removed or added?

ChessWhiz
If you add another class to the container div to indicate the number of columns:<div class="container two"> <div class="child">One</div> <div class="child">One</div></div>you can override these defaults with:.container.two .child { width:50%}
jjacka
The last question you have asked there is awesome. I am also wondering whether there is a way to do so.
Braveyard
You could use jQuery to get the parent container's width then calculate and set the child container widths. You could feasibly also count the number of child divs to calculate the size based on that number.
Brent Friar
@Brent, that's not a bad idea, but I'm wondering if it can be done with pure CSS.
ChessWhiz
+1  A: 

Total width is 500 so each child div should be 125px wide. You got the right idea using the float:left;

jeffkee
+1  A: 

The solutions that have been given to you are correct. Just be careful if you have margins/borders/paddings in the inner divs, because in that case the 25% would break the layout (margin, borders and paddings are not included in the percentage).

Laz75