Tarik
Tarik

Reputation: 81721

Fit divs into fixed space

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.

Upvotes: 0

Views: 284

Answers (4)

Fra Sprea
Fra Sprea

Reputation: 306

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).

Upvotes: 1

ChessWhiz
ChessWhiz

Reputation: 4702

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?

Upvotes: 2

jeffkee
jeffkee

Reputation: 5238

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

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630429

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

.child { width 25%; }

You can test it out/play with it here.

Upvotes: 2

Related Questions