【问题标题】:How to make multiple divs always fill out the whole browser size?如何让多个 div 总是填满整个浏览器的大小?
【发布时间】:2014-08-07 21:45:37
【问题描述】:

我想要一个div,它应该填满整个屏幕的宽度和高度。在 div 里面我想添加其他几个 div 不知道到底有多少(可能是 3,但也可能是 40)。是否可以仅使用 CSS 技术使这些 divs 填充周围 div 的整个宽度和高度?因此,当只有四个 divs 时,它们需要比有 40 个 divs 时大得多。我尝试使用 Flexbox 实现此效果,但没有成功。

【问题讨论】:

  • 为什么不使用width:100%; height: 100%; position: relative;为每个?
  • 使用百分比会有所帮助。
  • 你能用javascript/jQuery吗?
  • 想知道为什么有人会否决我的问题,这很难理解吗?正如我提到的,我只想要没有 JavaScript 的纯 CSS 技术。我不能使用固定百分比,因为我不知道divs 的数量。

标签: html css flexbox


【解决方案1】:

看看这个Demo

HTML:

<div id="wrap">
    <div class="inner">1</div>
    <div class="inner">2</div>
    <div class="inner">3</div>
    <div class="inner">4</div>
</div>

CSS:

#wrap {
position:absolute;
border:1px solid black;
height:100%;
width:100%;
display:flex;
flex-flow:row wrap;
justify-content:space-around;
}

.inner {
position:realtive;
border:1px solid red;
background-color:silver;
height:100%;
width:20%;
}

这里的棘手部分是设置.inner 元素的宽度。
因为它是百分比,所以你应该做的是将 100 除以 .inner 元素的数量。
这里有 4 个 .inner 元素,因此 100%/4 = 25%。这 25% 将是您的 .inner 元素的宽度。
但是我将宽度设置为 20%,为什么?因为#wrap 元素的justify-content:space-around;flex-flow:row wrap; 属性。
如果我将.inner 元素的宽度设置为 25%,则一个元素将环绕到底部。
您应该能够自己检测到最接近的值,其中.inner 元素不会包裹到底部。在这种情况下,最接近的宽度值为 20%。

【讨论】:

  • 谢谢,但如果 .inner 元素的数量不固定但可以变化,这将不起作用,我错了吗?
  • 您可以添加任意多个编号。 .inner 元素的数量随心所欲。但是如果你增加或减少编号。 .inner 元素的宽度,那么您将不得不更改 .inner 元素的宽度。我已经在答案的最后一部分解释了更改 .inner 元素宽度的过程。
  • @UmairKhan,我认为 OP 正在尝试构建页面以处理动态数量的 .inner 元素
【解决方案2】:

试试这个(DEMO 将随机的 DIV # 附加到 BODY,然后按百分比调整它们的大小):

CSS:

html, body {
  height: 100%;
  min-height: 100%;
}
body { 
  position: relative; 
  margin: 0; 
  paddding: 0; 
}
div { 
  width: 100%; 
  position: relative; 
}

JQuery:

$('div').css("height",(100/$('div').length) + "%");
// this sets the heights to equal percentages

【讨论】:

  • 谢谢,但我正在寻找纯 CSS 解决方案。
  • 我添加了一个替代的纯 CSS 解决方案作为不同的答案。
【解决方案3】:

这是我为我的问题找到的解决方案:Filling space with Flexbox

【讨论】:

    【解决方案4】:

    纯 CSS3 解决方案:DEMO

    (这涉及使用许多单独的样式规则 - 如果您的最大 DIV 数为 40,则为 40)

    html, body { height: 100%; min-height: 100%; }
    body { position: relative; margin: 0; paddding: 0; }
    div.inner { width: 100%; position: relative; }
    // this is where the CSS3 magic happens - these selectors can catch for an individual 
    // case in regards to the count of items on the page
    /* one item */
    div.inner:first-child:nth-last-child(1) { height: 100%; }
    /* two items */
    div.inner:first-child:nth-last-child(2), div.inner:first-child:nth-last-child(2) ~ div.inner { height: 50%; }
    /* three items */
    div.inner:first-child:nth-last-child(3), div.inner:first-child:nth-last-child(3) ~ div.inner { height: 33.3333%; }
    //...and so on up until your desired maximum of items...
    

    Reference

    IE9+支持

    【讨论】:

      猜你喜欢
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多