artparks
artparks

Reputation: 761

Three floated divs expand to fill container width

I don't think this is possible in pure CSS. I have three floated elements within a wrapping container and I want the central of the three to be the width of its content and those either side to fill in the remaining gaps left and right of this element.

<style>
.wrap {
    width: 50%;
    height: 100px;
    background: green;
}
.cont {
    background: red;
    float: left;
    display: inline-block;
    height: 100px;
}
.c1, .c3 {
    background: blue;
    width: auto;
}
</style>



<div class="wrap">
    <div class="cont c1">&nbsp;</div>
    <div class="cont c2">content</div>
    <div class="cont c3">&nbsp;</div>
</div>

http://jsfiddle.net/6eLdboqw/1/

I realise this is trivial in Javascript but I want to know if there's a pure CSS solution.

Upvotes: 0

Views: 74

Answers (2)

Nico O
Nico O

Reputation: 14102

You could do so using flexbox.

Here is a demo: http://jsfiddle.net/6eLdboqw/3/

.wrap {
    width: 400px;
    height: 100px;
    background: green;
    display: flex;
}

.c1, 
.c3
{
    flex: 1 1 auto;
}

.c2
{
    flex: 0 0 auto;
}

.cont {
    background: red;
    height: 100px;

}
.c1, .c3 {
    background: blue;
    width: auto;
}

flex is the short-hand property for: flex-grow, flex-shrink, flex-basis. So what we do is: .c1, .c3 may grow and shrink, but .c2 may not grow or shrink.

Upvotes: 0

SW4
SW4

Reputation: 71160

You could accomplish this by using CSS tables, with the middle div having a width of 1% to 'auto shrink':

.wrap {
  width: 400px;
  height: 100px;
  background: green;
  display: table;
}
.cont {
  background: red;
  display: table-cell;
  height: 100px;
}
.c1,
.c3 {
  background: blue;
  width: auto;
}
.c2 {
  width: 1%;
}
<div class="wrap">
  <div class="cont c1">&nbsp;</div>
  <div class="cont c2">content</div>
  <div class="cont c3">&nbsp;</div>
</div>

Upvotes: 2

Related Questions