Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto stretching column width with CSS

I think similar question must have been asked already, but I don't know how to find it...

I want to create a multi-column HTML layout with autostretching columns. Let's say 2 columns. When there's only one column on a page it fills 100% of container width, when I add a second column of 25% the first one automatically squeeze to 75%.

<div class="wrapper">
    <div class="content">...</div>
    <div class="sidebar">...</div>
</div>

I'm sure this can be done with JavaScript (checking if second column exists), but what about plain CSS? Is it actually possible? I need to support IE 9+.

like image 825
Andrey Avatar asked Mar 21 '26 09:03

Andrey


2 Answers

This can be done with css selectors:

  .content{
    width:100%;
  }
  .sidebar{
    width:25%;
  }
  .content:not(:only-child){
    width:75%;
  }

Pen: http://codepen.io/vandervals/pen/zGqorj

I think this is far more elegant than the table solution and the support is really wide: http://caniuse.com/#search=only-child

like image 103
Vandervals Avatar answered Mar 23 '26 21:03

Vandervals


You need something like following. Use display:table to parent and display:table-cell to child element.

.wrapper{
    display:table;
    width: 100%;
}

.content{
    display:table-cell;
    background-color:yellow;
}

.sidebar{
    display:table-cell;
    width:25%;
    background-color:blue;
}
<div class="wrapper">
    <div class="content">...</div>
    <div class="sidebar">...</div>
</div>

Hope it helps.

like image 35
ketan Avatar answered Mar 23 '26 22:03

ketan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!