[英]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. 我想创建一个带有自动伸展列的多列HTML布局。 Let's say 2 columns. 我们说2列。 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%. 当页面上只有一列时,它会填充100%的容器宽度,当我添加25%的第二列时,第一列自动挤压到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? 我确信这可以用JavaScript完成(检查第二列是否存在),但是纯CSS呢? Is it actually possible? 它真的可能吗? I need to support IE 9+. 我需要支持IE 9+。
You need something like following. 你需要像以下一样的东西。 Use display:table
to parent and display:table-cell
to child element. 使用display:table
到parent并display:table-cell
to 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>
Hope it helps. 希望能帮助到你。
This can be done with css selectors: 这可以通过css选择器完成:
.content{
width:100%;
}
.sidebar{
width:25%;
}
.content:not(:only-child){
width:75%;
}
Pen: http://codepen.io/vandervals/pen/zGqorj 笔: 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 我认为这比桌面解决方案更优雅,支持范围很广: http : //caniuse.com/#search=only-child
I know you ask for a CSS solution, but here is a simple jQuery script to have a dynamic sizing (no matter the number of column, it will be divided and fit in the row). 我知道你要求一个CSS解决方案,但是这里有一个简单的jQuery脚本,可以进行动态调整(无论列数是多少,它都会被划分并适合行)。
$(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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.