Stretch width with CSS

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

I want to create an HTML multicolumn layout with auto-configuring columns. Let's say 2 columns. When there is only one column on the page, it fills 100% of the container width, when I add the second column at 25%, the first one automatically shrinks to 75%.

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

      

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

+3


source to share


3 answers


This can be done using 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 much more elegant than a tabular solution and the support is really wide: http://caniuse.com/#search=only-child

+2


source


You need something like the following. Use display:table

for parent and display:table-cell

child.



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

Run codeHide result


Hope it helps.

+2


source


I know you are asking for a CSS solution, but there is a simple jQuery script here for sizing dynamically (regardless of the number of columns, it will be split and put in a row).

$(document).ready(function() {
	$('.row').each(function(k, v) {
		var col =  $('.column', this),
			colNumber  = col.length,
			percent = 100 / colNumber;
			console.log(percent);
		col.css({'width' : percent + '%'});
	});	
});
      

* {
	box-sizing: border-box;
}
.wrapper {
	width: 960px;
	margin: 0 auto;
}
.column {
	float: left;
	height: 200px;
	margin: 0 auto;
	border: 1px solid black;
	background-color: orange;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
	<div class="row">
		<div class="column"></div>
		<div class="column"></div>
	</div>
	<div class="row">
		<div class="column"></div>
	</div>
	<div class="row">
		<div class="column"></div>
		<div class="column"></div>
		<div class="column"></div>
	</div>
</div>
      

Run codeHide result


+2


source







All Articles