绝对定位和改变固定高度

时间:2015-04-21 11:40:37

标签: html css

我正在处理绝对和相对的很多位置,以便为这个项目获得正确的布局。正如你可以在我的小提琴中看到的那样,黑色背景的高度设置为一个固定的高度,因为如果我不这样做就不会显示。

我的问题是,是否有办法将此高度设置为仅填充窗口?因为固定高度你有一个我想避免的滚动条或空格

我的Fiddle

HTML

<div class="section">
  <div class="header">
    <img src="http://placehold.it/100x100&text=logo" alt="logo" />
  </div>
  <div class="header-bg"></div>
</div>

<div class="box">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius aspernatur nemo voluptatem provident fuga     beatae. Dolore explicabo laborum laboriosam debitis eligendi rerum quis nam facere inventore magnam eum nisi sed
  </p>
</div>
<div class="box-bg"></div> 

CSS

.section {
  height: 150px;
  margin-bottom: 20px;
}
.header {
  position: absolute;
  z-index: 100;
  width: 100%;
}
.header img {
  display: block;
  margin: 0 auto;
  width: 100px;
}
.header-bg {
  position: relative;
  top: 25px;
  background: green;
  height: 50px;
  width: 100%;
}
.box {
  position: absolute;
  z-index: 200;
  width: 100%;
}
.box p {
  width: 300px;
  height: 200px;
  background: lightgrey;
  margin: 0 auto;
}
.box-bg {
  position: relative;
  top: 100px;
  background: black;
  height: 600px;
}

2 个答案:

答案 0 :(得分:4)

使用底部位置:(而不是使用高度):(并将位置更改为绝对位置。)

.box-bg {
    position: absolute;
    top: 270px;
    background: black;
    bottom: 0;
    width: 100%;
}

Updated Fiddle

答案 1 :(得分:1)

CSS视口高度可以用来实现这样的事情,但它取决于你支持的浏览器:http://caniuse.com/#feat=viewport-units

另外,从小提琴中难以想象你想要实现的目标。你能解释一下吗?

黑色区域可能只是身体背景颜色?