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

zpjtge22  于 2023-06-25  发布在  其他
关注(0)|答案(6)|浏览(118)

我有两个容器div内的div,我需要设置他们都适合浏览器窗口如下,但它不适合我的代码,请建议我一个解决方案

我的样式表代码

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>
ryhaxcpt

ryhaxcpt1#

如果你不关心老式IE,你也可以使用视口百分比。
height: 100vh;

n6lpvg4x

n6lpvg4x2#

为空div设置窗口全高
第一种解决方案,采用绝对定位-FIDDLE

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

第二种解决方案用静态(也可以用相对)定位& 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() });
  });
});
46scxncf

46scxncf3#

伙计,试试最小高度。

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

ie3xauqp4#

你必须声明html到div1元素的高度,比如:

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

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

cngwdvgl

cngwdvgl5#

我不认为你需要浮动。

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;
}
<div class="container">
  <div class="div1"></div><!--
  --><div class="div2"></div>
</div>

display: inline-block;用于将块显示为内联(就像跨度,但保持块效果)
使用html中的注解是因为你有75%+25%= 100%。div之间的空格计数(所以你有75%+1%?+25%= 101%,表示换行符)

44u64gxh

44u64gxh6#

我认为最快的方法是使用分数网格系统。所以你的容器有100vw,这是100%的窗口宽度和100vh,这是100%的窗口高度。
使用分数或'fr',您可以选择您喜欢的宽度。分数之和等于100%,在本例中为4FR。所以第一部分是1fr(25%),第二部分是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>

相关问题