【问题标题】:Keeping aspect ratio for images with percentage width & resizing other divs while keeping aspect ration保持具有百分比宽度的图像的纵横比并在保持纵横比的同时调整其他 div 的大小
【发布时间】:2018-01-11 04:02:22
【问题描述】:

我正在尝试找出一种方法,使图像 div 具有并保持 3:2 的纵横比和不同的网络浏览器尺寸(用于移动响应等)。我希望能够重新调整我的浏览器窗口和图像的大小,使其始终具有 3:2,因此我希望图像高度也能重新调整大小。

有没有办法用我当前的代码实现这一点?我还希望能够使蓝色文本 div 更小,而不必使上面的图像更大,因为如果我降低蓝色 div 的高度百分比,我将不得不增加上面的图片 div 来弥补100% 父元素的高度,但这会抛出图片 div 的纵横比。

我不确定如何实现这一点,因为它比我想象的更令人困惑。

感谢任何帮助,谢谢...

#bg {
  width: 100%;
  height: 300px;
  background: yellow;
}
#window-container {
  width: 30%;
  height: 200px;
  background: orange;
}
#img {
  background: url('http://www.livescience.com/images/i/000/036/988/original/elephants.jpg');
  height: 67%;
  width: 100%;
  background-size: cover;
  background-position: center;
}
#text-wrap {
  background: lightblue;
  width: 100%;
  height: 33%;
}
<div id="bg">
  <div id='window-container'>
    <div id='img'></div>
    <div id='text-wrap'>text here</div>
  </div>
</div>

【问题讨论】:

  • 你很幸运。 %-paddingmargin 的值始终引用元素的 width,即使应用于 padding-bottompadding-top。有了这些知识,您应该能够轻松找到确保纵横比保持不变的解决方案。
  • 还是不确定。应用边距不会增加图像和蓝色 div 之间的差距,并且填充只会将文本向下推,但蓝色 div 会保持相同的大小?
  • 其他宽度和高度值的灵活性如何?
  • 只要保持纵横比并且蓝色 div 可以调整大小就可以了

标签: html css


【解决方案1】:

这就是你想要的吗?

#bg {
  width: 100%;
  background: yellow;
  display: table;
}
#window-container {
  width: 30%;
  background: orange;
  display: block;
}
img {
  width: 100%;
  height: auto;
}
#text-wrap {
  background: lightblue;
  padding: 10px;
}
<div id="bg">
  <div id='window-container'>
    <img src="https://www.livescience.com/images/i/000/036/988/original/elephants.jpg" alt="">
    <div id='text-wrap'>text here</div>
  </div>
</div>

【讨论】:

  • 好像是这样,谢谢!大概您可以使用填充调整蓝色 div 的“高度” - 或者无论如何,它似乎会响应其高度以容纳更多文本
  • 不垂直响应。
  • 什么意思?调整浏览器窗口的大小也会调整图像的大小以保持其纵横比
  • @VXp 垂直响应?
  • 从下方调整大小。
【解决方案2】:

您可以使用 img 元素和 Flexbox

#bg {
  background: yellow;
}

#window-container {
  display: inline-flex; /* only takes the contents width */
  flex-direction: column; /* stacks children vertically */
  background: orange;
}

#text-wrap {
  background: lightblue;
}

img {
  display: block; /* removes bottom margin/whitespace */
  /*height: 66.66%; more accurate, needs to be commented out in order to work in Chrome, in FF it works perfectly, so the solution is to use properly cropped (3:2 ratio) locally stored images, luckily that's not the case with the current image*/
  max-width: 100%; /* horizontal responsiveness */
  max-height: 100vh; /* vertical responsiveness */
}
<div id="bg">
  <div id='window-container'>
    <img src="http://www.livescience.com/images/i/000/036/988/original/elephants.jpg" alt="">
    <div id='text-wrap'>text here</div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2013-06-26
    • 2012-04-15
    相关资源
    最近更新 更多