【发布时间】:2016-09-07 12:50:29
【问题描述】:
我正在寻找纯 CSS 解决方案。
我在下图中说明了我的问题。
- 黑色:具有百分比高度的父容器
- 白色:我的图像容器将此高度作为他的最大高度
- 红色:图像本身,按比例调整大小并垂直居中
- 黑色和灰色文本:下方的标题,粘贴在图片的左下角,ANY 变体如下所示
我的主要问题是,如果文本比图像宽,则让文本换行。这是通过 flexbox 实现的,但它没有按照我想要的方式工作。
有人遇到同样的问题,或者有人可以帮忙吗?
我知道许多图像对齐技术,并且我可以用 JS 解决我的问题,但我正在寻找纯 CSS 的解决方案。
编辑:我要注意,这是 3 张不同的图片。
这是JSFiddle!
.parent {
position: relative;
width: 100%;
height: 500px;
}
.other-content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 50%;
color: #fff;
background: #efefef;
}
.content-container {
position: absolute;
height: 50%;
width: 100%;
bottom: 0;
left: 0;
background: #000;
}
.scrollable-content {
width: 100%;
height: 100%;
overflow: auto;
}
figure {
height: 100%;
background: #fff;
margin: 0 0 20px 0;
display: flex;
flex: 0 1 auto;
flex-direction: row;
flex-flow: wrap;
justify-content: center;
align-items: flex-start;
}
img {
max-height: 100%;
max-width: 100%;
}
figcaption {
font-family: Verdana, sans-serif;
font-size: 12px;
color: #ccc;
}
.credit {
display: block;
color: #888;
}
<div class="parent">
<div class="other-content">
OTHER CONTENT HERE
</div>
<div class="content-container">
<div class="scrollable-content">
<figure class="img-container">
<img src="http://dummyimage.com/993x993/db0000/fff" alt="Lorem ipsum" />
<figcaption class="caption">
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore
<span class="credit">At vero eos et accusam</span>
</figcaption>
</figure>
<figure class="img-container">
<img src="http://dummyimage.com/993x200/db0000/fff" alt="Lorem ipsum" />
<figcaption class="caption">
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore
<span class="credit">At vero eos et accusam</span>
</figcaption>
</figure>
<figure class="img-container">
<img src="http://dummyimage.com/200x993/db0000/fff" alt="Lorem ipsum" />
<figcaption class="caption">
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore
<span class="credit">At vero eos et accusam</span>
</figcaption>
</figure>
</div>
</div>
</div>
【问题讨论】:
-
一个快速的谷歌搜索出现了several CSS solutions。
-
@Michael_B:我知道这些解决方案。他们没有为图像提供最大高度。你能让我的代码与这些解决方案一起工作吗?我在前 3 个结果页面上测试了所有方法
-
考虑将
figure元素设置为flex-direction: column,这将垂直堆叠图像和标题。然后管理弹性容器的宽度。 (并反转justify-content和align-items中的值。) -
@Michael_B:更新了我的示例。是我的错,我尝试了很多,以至于我错过了添加正确的值。 Fiddle 现在应该可以工作了。但是标题在底部用完了框,并且标题与图像不对齐
-
感谢您的澄清。我误解了你问题的一部分。总而言之,我不确定如何在没有 JS 的情况下将标题限制为图像的宽度。下班后我会回来回答这个问题。
标签: html css alignment flexbox