【发布时间】: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 哦,你是对的,只要设置宽度就可以了,我觉得自己像个白痴,不早点尝试,哈哈