将各种大小的div元素适合于整个容器的宽度

  • 本文关键字:适合于 元素 div css css-float
  • 更新时间 :
  • 英文 :


我在各种浮动div元素中有一个div容器:我想有一些宽(大)的,另一些宽(小)的;同时,所有这些都应该适合整个容器宽度。small、big和total元素的数量是通过javascript动态设置的,所以我不能在css中使用固定的百分比宽度。

在一些GUI开发人员软件中,有一些伸缩值可以实现这一目标。

示例(静态)html:

<div class="container">
    <div class="small">small</div>
    <div class="big">BIG</div>
    <div class="big">BIG</div>
    <div class="big">BIG</div>
    <div class="small">small</div>
</div>

示例css:

.container {
    display: block;
    overflow: hidden;
    width: 100%; }
.big , .small {
    float: left; }

谢谢!

选项1:CSS Flex框

您可以为此使用CSS flex box:

.container {
  display:flex;
  flex-wrap:nowrap;
}
    
.big {
  flex-grow:2;
  background-color:red;
}
.small {
  flex-grow:1;
  background-color:yellow;
}
<div class="container">
    <div class="small">small</div>
    <div class="big">BIG</div>
    <div class="big">BIG</div>
    <div class="big">BIG</div>
    <div class="small">small</div>
</div>

选项2:JavaScript

您可以创建一个JS方法来计算所需的总宽度,并设置与之相比较的css样式。

理论:

Small = 1 width
Big = 2 width

查看此链接可以计算div中的项目数:https://api.jquery.com/length/

4x big = 8 width
5x small = 5 width
total width = 13 width
width per small  in % = 100 / 13
width per large  in % = 100 / 13 * 2

设置宽度(例如使用JQuery)

最新更新