如何使多个div总是填写整个浏览器大小?

时间:2014-08-06 20:50:05

标签: html css3 flexbox

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

4 个答案:

答案 0 :(得分:0)

查看此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%,为什么呢?由于justify-content:space-around;元素的flex-flow:row wrap;#wrap属性 如果我将.inner元素的宽度设置为25%,则一个元素将换行到底部 您应该能够自己检测最近的值,其中.inner元素不会包裹到底部。在这种情况下,最接近的宽度值为20%。

答案 1 :(得分:0)

试试这个(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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

纯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 +

中受支持
相关问题