【发布时间】:2018-09-27 01:20:51
【问题描述】:
我正在尝试将容器内的图像居中并缩放。在下图中,粉色框是 16:9 的容器,蓝色框是图像。
正如您在图表中看到的,还有一个 caption div 与图像的左下方对齐,一个 关闭图标 与右上方对齐。
这是我现在拥有的代码:
/* The page */
.container {
width: 100%;
height: 100%;
}
/* 16:9 container */
.imageWrapper {
padding-bottom: 56.25%;
position: relative;
width: 100%;
border: 1px solid red;
}
.imageInnerWrapper {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: center;
}
/* The image, footer and close button all need to fit inside the container */
.imageAndFooterWrapper {
display: inline-flex;
flex-direction: column;
position: relative;
border: 1px solid lightblue;
}
.image {
max-height: 100%;
object-fit: contain;
}
.footer {
text-align: left;
}
.closeButton {
position: absolute;
top: -30px;
right: -30px;
}
<div class="container">
<div class="imageWrapper">
<div class="imageInnerWrapper">
<div class="imageAndFooterWrapper">
<img class="image" src="https://images.theconversation.com/files/204986/original/file-20180206-14104-1hyhea9.jpg?ixlib=rb-1.1.0&rect=0%2C1212%2C5550%2C2775&q=45&auto=format&w=1356&h=668&fit=crop">
<div class="footer">
Caption
</div>
<div class="closeButton">X</div>
</div>
</div>
</div>
</div>
以下 CodePen 包含上述代码,以及一些不同大小图像的示例。
【问题讨论】:
-
这可能与此重复:stackoverflow.com/questions/12991351/… -- 如果不是完全重复,那里仍有信息可以帮助您。
-
@Zephyr 为什么不删除
标签并使用带有背景大小的 background-image 属性?
-
@kshetline 谢谢,但我的问题非常不同和具体,我不仅要处理单个图像,还要处理特定大小的容器和绝对定位的关闭图标和页脚。实际上,我确实已经合并了该答案,我的图像具有
max-height: 100%; object-fit: contain;以将比例和大小保持在imageAndFooterWrapper内。 -
@user6016913 我不能使用
background-image,因为它不知道图像的宽度,并且页脚和关闭按钮都需要知道图像的尺寸才能进行绝对定位。 (对不起,我之前发布了一个错误的评论,说问题是它裁剪了图像) -
@Zephyr 你得到你的答案还是你仍然陷入设计问题,如果是,那么我会尽力给你一个答案。其实我一直在关注问题,但由于时间不够,我无法给你答案,但现在我可以了,所以先问你
标签: javascript html css flexbox