使用CSS设置div高度以适合浏览器

时间:2013-09-21 15:05:43

标签: html css

我在容器div中有两个DIV,我需要将它们设置为适合浏览器窗口,如下所示,但它不适合我的代码,请建议我解决方案

enter image description here

我的样式表代码

 html, body {
                width: 100%;
                height: 100%;
                margin: 0;
                padding: 0;

            }

.container {
    height: auto;
    width: 100%;
}
.div1 {
    float: left;
    height: 100%;

    width: 25%;
}
.div2 {
    float: left;
    height: 100%;
    width: 75%;
}

<body>
<div class="container">
  <div class="div1"></div>
  <div class="div2"></div>
</div>

6 个答案:

答案 0 :(得分:52)

如果您不关心旧学校IE,也可以使用viewport percentages

height: 100vh;

答案 1 :(得分:34)

为空div设置窗口全高

具有绝对定位的第一个解决方案 - FIDDLE

.div1 {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 25%;
}
.div2 {
  position: absolute;
  top: 0;
  left: 25%;
  bottom: 0;
  width: 75%;
}

第二种具有静电的解决方案(也可以用于相对的)定位&amp; jQuery - FIDDLE

.div1 {
  float: left;
  width: 25%;
}
.div2 {
  float: left;
  width: 75%;
}

$(function(){
  $('.div1, .div2').css({ height: $(window).innerHeight() });
  $(window).resize(function(){
    $('.div1, .div2').css({ height: $(window).innerHeight() });
  });
});

答案 2 :(得分:3)

男人,试试最小高度。

.div1 {
    float: left;
    height: 100%;
    min-height: 100%;
    width: 25%;
}
.div2 {
    float: left;
    height: 100%;
    min-height: 100%;
    width: 75%;
}

答案 3 :(得分:2)

我认为你不需要浮动。

&#13;
&#13;
html,
body,
.container {
  width: 100%;
  height: 100%;
}

.div1, .div2 {
  display: inline-block;
  margin: 0;
  min-height: 100%;
}

.div1 {
  width: 25%;
  background-color: green;
}

.div2 {
  width: 75%;
  background-color: blue;
}
&#13;
<div class="container">
  <div class="div1"></div><!--
  --><div class="div2"></div>
</div>
&#13;
&#13;
&#13;

display: inline-block;用于将块显示为内联(就像跨距但保持块效果)

使用html中的注释,因为你有75%+ 25%= 100%。 div之间的空间计数(所以你有75%+ 1%?+ 25%= 101%,意味着换行)

答案 4 :(得分:1)

你必须将html的高度声明为div1元素,例如:

html,
body,
.container,
.div1,
.div2 {
    height:100%;
}

演示:http://jsfiddle.net/Ccham/

答案 5 :(得分:1)

我认为最快的方法是使用带有分数的网格系统。 所以你的容器有 100vw,它是窗口宽度的 100%,100vh 是窗口高度的 100%。

使用分数或“fr”,您可以选择您喜欢的宽度。分数的总和等于 100%,在本例中为 4fr。所以第一部分将是 1fr (25%) 而 seconf 是 3fr (75%)

有关 fr 单位 here 的更多信息。

.container{
  width: 100vw;
  height:100vh; 
  display: grid;
  grid-template-columns: 1fr 3fr;
}

/*You don't need this*/
.div1{
  background-color: yellow;
}

.div2{
  background-color: red;
}
<div class='container'>
  <div class='div1'>This is div 1</div>
  <div class='div2'>This is div 2</div>
</div>