【问题标题】:CSS: 100% height relative to the outer of two surrounding div's?CSS:相对于两个周围 div 的外部的 100% 高度?
【发布时间】:2013-06-20 19:39:40
【问题描述】:

我整个下午都在为此苦苦挣扎,所以我想我会寻求帮助...

基本上,我有以下结构:

<div id="gallery">

  <div class="product">
    <img ... />
    <div class="caption">
      <p>some text</p>
    </div>
  </div>

  <div class="product">
    <img ... />
    <div class="caption">
      <p>some text</p>
    </div>
  </div>

</div>

简而言之,我想实现以下目标:

  • 外部容器 (div#gallery) 随浏览器窗口缩放(高度:100%;)。
  • 图像相对于外部容器 div#gallery 缩放(高度:100%;宽度:自动;),从而使它们具有响应性。
  • 每个内部容器 (div.product) 的宽度紧紧地包围了其中包含的图像。
  • 字幕 (div.caption) 相对于 div.product 定位为“绝对”(它们被透明背景覆盖,但这不是重点)。

第一次尝试:我可以简单地编写以下 CSS:

div#gallery {position: relative; height: 100%; ...}
img         {height: 100%; width: auto;}
div.caption {position: absolute; width: 100%; ...}

这样,div.product 将是“静态的”,并且图像将相对于 div#gallery 定位。不幸的是,我需要 div.product 是“相对”的 div.caption 才能工作。所以...

div#gallery {position: relative; height: 100%; ...}
div.product {position: relative;}
img         {height: 100%; width: auto;}
div.caption {position: absolute; width: 100%; ...}

嗯,div.caption 现在可以工作了,但是 img 的高度现在是相对于 div.product 的,它不会缩放。所以,让我们添加...

div#gallery {position: relative; height: 100%; ...}
div.product {position: relative; height: 100%; width: auto;}
img         {height: 100%; width: auto;}
div.caption {position: absolute; width: 100%; ...}

现在,这应该真的有效,不是吗!?嗯,差不多。还有一个奇怪的地方:在调整浏览器大小时, div.product 的高度会按原样缩放,但宽度仍固定在其中包含的图像的原始宽度!

这就是我卡住的地方。有什么想法吗?

非常感谢您!

编辑:根据两个建议,现在有一个 jsFiddle 来说明这种情况:http://jsfiddle.net/marccee/vx5DC/2/

【问题讨论】:

  • 如果您创建了一个您描述的最后/几乎工作状态的 jsFiddle,将会很有帮助。
  • 感谢您的建议。我对 jsFiddle 没有太多经验,所以我只是简单地编辑了 dwreck08 的代码以更好地反映我的情况(感谢您设置它)...希望有效:jsfiddle.net/marccee/vx5DC/2 调整浏览器窗口大小时可以看到问题:图像按应有的比例缩放,但周围的 div.product 不跟随。相反,它们似乎保持固定在图像的原始 (!) 宽度上。

标签: css responsive-design


【解决方案1】:

我正在尝试关注您的帖子,但里面有很多信息!

看看这是否在正确的轨道上:http://jsfiddle.net/derekstory/vx5DC/1/

html, body {
    height: 100%;
    width: 100%;
    margin: 0;
}
#gallery {
    height: 100%;
    width: 100%;
}
.product {
    background: #333;
    height: 100%;
    width: 100%;
}
.image {
    position: absolute;
    background: #777;
    height: 100%;
    width: 100%;
}
.caption {
    background: rgba(111, 444, 333, .1);
    width: 100%;
    height: 100%;
    position: absolute;
}

【讨论】:

  • 感谢您进行设置。我对 jsFiddle 没有太多经验,所以我只是编辑了您的代码以更好地反映我的情况...希望有效:jsfiddle.net/marccee/vx5DC/2 调整浏览器窗口大小时可以看到问题:图像按应有的比例缩放,但周围的 div.product 不跟随。相反,它们似乎保持固定在图像的原始 (!) 宽度上。
  • 看看这是否更符合您的需求:jsfiddle.net/derekstory/vx5DC/4
  • 嗯,这基本上可行,但不是我需要的方式。我需要拉伸图像的高度以填充可用空间。宽度应相应调整。在你的情况下,宽度缩放并且高度适应......
  • 感谢您的帮助。我注意到,您将 .product 替换为 .contain ...您能否简要解释一下您要做什么?我不确定,您在哪个浏览器中工作...我在 Firefox 中查看此内容,现在图像非常大。实际上,我希望图片的高度是#gallery 的 100%。
  • 哇!那些在FF中很大。我没有检查FF。铬看起来不错..哎呀。我想我只是不小心删除了 .product 标签并用我自己的标签替换它,因为我不记得名字了。同样的事情。
猜你喜欢
  • 1970-01-01
  • 2018-05-27
  • 1970-01-01
  • 2015-09-06
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 2012-11-23
  • 2011-07-22
相关资源
最近更新 更多