将文本对齐到随机图像下方。

4

我需要将文本对齐在图像下方,因此文本不应超过图像宽度。 然而,这些图像是随机选择的,在php中选择它们时它们的高度和宽度并不相同。

我找到了许多解决方案,但它们都涉及将固定宽度设置为容器,这是我无法做到的,因为图像大小可能会变化。

以下是我的代码,没有容器宽度:

.container {
  position: relative;
}

.reward-complete-image {
  max-width: 70vw;
  max-height: 70vh;
}
<div class="container">
  <figure>
    <img class="reward-complete-image" src="https://wallpapercave.com/wp/bvJq0ra.jpg">
    <figcaption>This picture can change it is dynamically generated, thus other images could have a different width and height. This is why the solution should allow for the text under the image to be ".</figcaption>
  </figure>
</div>

如果现有的CSS是为了其他原因而存在的,您可以根据需要进行更改。 我使用了figure和ficaption,但如果您喜欢,可以随意使用其他旧标签。

我尝试将百分比宽度应用于容器,或者将最大宽度应用于百分比或固定像素数,但所有这些都不起作用,文本仍然超出图像。 如果可能的话,我更喜欢只使用HTML和CSS,而不使用Javascript。我还将现有的HTML放在一个列中的表格中,但文本仍然超出图像。

如何在不知道图像的宽度和高度的情况下使文本与图像对齐?

谢谢

2个回答

1
如果您希望文本宽度与给定图像相同,则需要在figure中添加display: table-caption;,如下所示:

.container {
  position: relative;
}

.reward-complete-image {
  max-width: 70vw;
  max-height: 70vh;
}

figure {
  display: table-caption;
}
<div class="container">
  <figure>
    <img class="reward-complete-image" src="https://wallpapercave.com/wp/bvJq0ra.jpg">
    <figcaption>This picture can change it is dynamically generated, thus other images could have a different width and height. This is why the solution should allow for the text under the image to be ".</figcaption>
  </figure>
</div>


0
您可以尝试使用一个网格布局,它会自动调整到您的图像大小。就像这样:

.container {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: auto auto;
  grid-row-gap: 10px;
  text-align: center;
}

.reward-complete-image {
  max-width: 100%;
  height: auto;
}

figcaption {
  grid-row-start: 2;
}
<div class="container">
  <figure>
    <img class="reward-complete-image" src="https://wallpapercave.com/wp/bvJq0ra.jpg">
    <figcaption>This picture can change it is dynamically generated, thus other images could have a different width and height. This is why the solution should allow for the text under the image to be ".</figcaption>
  </figure>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接