【问题标题】:Image resize, conform to max-width but change height to maintain aspect ratio图像调整大小,符合最大宽度但改变高度以保持纵横比
【发布时间】:2018-01-22 22:59:05
【问题描述】:

我一直在寻找这个问题的答案。我更喜欢只有 CSS 的解决方案,但我一直找不到。

我有一个固定宽度的弹出窗口,如果内容更大,它的高度会增加。在里面,我放了一个图像,它应该占据弹出窗口的一半,同时保持纵横比并尽可能大而不离开屏幕,还有一个 div 来保存关于图像的信息,它也应该是屏幕的一半,这样image 和 div 是并排的。此处示例:https://codepen.io/Smarticles101/pen/WdmZLx

我可以在90vh 的图像上设置一个高度以使其更大,并设置50% 的最大宽度以确保它只占用弹出窗口的一半。但是,如果窗口宽度缩小或我将弹出窗口的固定宽度变小,图像将保持高度和最大宽度,因此不会保持纵横比。

如何使图像在宽度缩小的同时保持纵横比?

HTML:

<div id="popup">
  <img src="https://images.freeimages.com/images/large-previews/12d/frangipani-02-1311438.jpg" alt="image" />
  <div id="sidedata">
    <h1>Image</h1>
    <p>Some data about the image here</p>

  </div>
</div>
<br />
<div id="popup">
  <img src="https://www.w3schools.com/images/w3schools_green.jpg" />

</div>

CSS:

#popup {
  max-width: 50%;
  background-color: blue;
}

img {
  height: 90vh;

  max-width: 50%;
  /*
    The image will not maintain aspect ratio if the max-width is reached, it will maintain height as whatever it was set to originally rather than     shrink in height.
  */

  display: inline-block;
}

#sidedata {
  max-width: 50%;
  display: inline-block;
}

【问题讨论】:

  • 一半是“一个在另一个之上”还是并排?
  • @FacundoCorradini 并排,我应该指定的。我会编辑我的问题来这样做
  • 并排应该只是将img宽度设置为50%并且没有指定高度
  • @FacundoCorradini 哦,你是对的,只要设置宽度就可以了,我觉得自己像个白痴,不早点尝试,哈哈

标签: html css image


【解决方案1】:

简短的回答,希望对您有所帮助,请尝试max-height

img {
  max-height: 90vh;
  max-width: 50%;
  display: inline-block;
}

【讨论】:

  • 发生了法语废话,抱歉 :)
猜你喜欢
  • 2015-05-22
  • 2015-01-21
  • 2021-02-09
  • 2013-04-03
  • 1970-01-01
  • 2011-12-27
  • 2021-06-12
  • 2013-07-29
  • 2019-10-11
相关资源
最近更新 更多