我正在尝试设置此样式:
<div class="figure"> <img src="/some/image.jpg"> <p class="caption"> <span class="caption-text">Some caption of any length</span> </p> </div>
以便标题位于与图像宽度相同的阴影框中。请注意,.figure有时可以将其<td>放在表的内部。它也不应超过父元素的宽度(必要时将图像缩小)。
.figure
<td>
这是我到目前为止的内容:
.caption-text { font-size: 14px; font-family: Lato, proxima-nova, 'Helvetica Neue', Arial, sans-serif; font-weight: normal; line-height: 0px; } .figure { max-width: 100%; display: inline-block; position: relative; } .figure img { vertical-align: top; margin-bottom: 3px; } .caption { display: block; width: 100%; position: absolute; padding: 10px; background-color: #e3e3e3; box-sizing: border-box; margin: 0; } <div style="width:500px"> <h1>Some Title</h1> <!--part I want to style--> <div class="figure"> <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150"> <p class="caption"> <span class="caption-text">Some caption of any length. Should wrap and push content down when longer than the image.</span> </p> </div> <p>Some text which should always go below the caption. When positioned absolutly the caption overlays this text, instead of pushing it down below.</p> </div>
问题在于,放置.captionas position:absolute;使其不再影响其他元素的流动,因此它会将其覆盖在其下方的内容上,而不是将其下推。
.caption
position:absolute;
html标记是自动生成的,我无法对其进行任何编辑,因此我想知道使用 纯css 是否可行。
您可以使用CSS display:table+ table-caption解决方案。
display:table
table-caption
.figure { display: table; margin: 0; } .figure img { max-width: 100%; } .figcaption { display: table-caption; caption-side: bottom; background: pink; padding: 10px; } <h3>Example of small image</h3> <figure class="figure"> <img src="//dummyimage.com/300x100" alt=""> <figcaption class="figcaption">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</figcaption> </figure> <h3>Example of large image</h3> <figure class="figure"> <img src="//dummyimage.com/900x100" alt=""> <figcaption class="figcaption">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</figcaption> </figure>