praks5432
praks5432

Reputation: 7772

Make child divs expand to fill parent div's width

I have three divs inside one div.

<div class="parent">
<div class="child"> Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
</div>

I want the child divs to fill up the width of the parent (the combined width of the children should be the parent). However, this is not happening, I'm falling short. I think this is because the child divs are setting width based on their content.

How do I achieve what I want?

CSS-

.child {
    background: white;
    color: #a7a9ac;
    cursor: pointer;
    font-size: 15px;
    border-right: 1px;
    border-top: 0;
    border-bottom: 0;
    border-left: 0;
    border-style: solid;
    border-color: @faded-grey;
    padding-right: 10px;
    margin: 0 auto;
    height: 100%;
}

.parent {
    border-top: 1px;
    border-left: 0;
    border-bottom: 1;
    border-style: solid;
    border-color: @faded-grey;
    border-right: 0;
    width: 100%;
    margin-right: 0px;
    height: 80px;

}

Upvotes: 17

Views: 64400

Answers (4)

Sheki
Sheki

Reputation: 1635

I'm surprised that no one suggested the css3 solution using flex namely:

.parent {
  display: flex;
  flex-wrap: wrap;
}

.child {
  flex: 1;
}

Upvotes: 3

Steven Linn
Steven Linn

Reputation: 698

I needed for my solution to accommodate a variance in the number of elements for them to be completely responsive.

I discovered an interesting solution to this. It essentially displays like a table. Every element shares available width, and this also works for images very well: http://jsfiddle.net/8Qa72/6/

.table {
    display: table;
    width: 400px;
}

.table .row {
    display: table-row;
}

.table .row .cell {
    display: table-cell;
    padding: 5px;
}

.table .row .cell .contents {
    background: #444;
    width: 100%;
    height: 75px;
}

Upvotes: 7

user1693593
user1693593

Reputation:

You can add these three properties to the .child CSS rule:

width:33%;
float:left;    
box-sizing: border-box;

The last line makes sure it will also work when you add borders, padding and margin to the boxes.

ONLINE DEMO

Ps: not directly related but there is also an error in the border-bottom for parent, corrected in fiddle above. When you use non-0 value you need to specify unit:

    border-bottom:1px;

Upvotes: 11

Jimmy Breck-McKye
Jimmy Breck-McKye

Reputation: 3034

If you know there will always be three children, you can simply use:

.parent > .child {
    float: left;
    width: 33%;
}

.parent {
    overflow: auto; /*or whatever float wrapping technique you want to use*/
}

If you do not know how many children there are, you will need to use CSS tables, flexbox, or perhaps combine inline-blocks with text-align: justify.

Upvotes: 13

Related Questions