我试图在图像下布置一些文本,图像决定容器的宽度,文本换行成几行以适应宽度。
我当前的代码如下所示:
.image-container {
display: inline-block;
text-align: center;
padding: 6px;
background-color: red; /* To highlight container size */
}
.image {
height: 120px;
}
.text-wrapper {
position:relative;
width: 100%;
}
.text {
position:absolute;
left:0px;
top:100%;
right:0px;
}
<div class='image-container'>
<img src='http://i.imgur.com/nV2qBpe.jpg' class="image">
<div class='text-wrapper'>
<p class='text'>Some text that may need to wrap into multiple lines</p>
</div>
</div>
但如您所见,由于文本是绝对定位的,所以它不是容器高度的一部分,因此无法在页面的其余部分正确布局。
如何正确解决这个问题?顺便说一句,我宁愿失去一些浏览器兼容性也不愿使用 js。
最佳答案
试试这个
.image-container {
display: table;
width: 1%;
}
img {
height: 120px;
}
.text {
overflow: hidden;
}
<div class='image-container'>
<img src='http://i.imgur.com/nV2qBpe.jpg' class="image">
<div class='text-wrapper'>
<p class='text'>Some text that may need to wrap into multiple lines</p>
</div>
</div>
这是您可以尝试的另一种解决方案
.image-container {
display: table;
}
img {
height: 120px;
}
.text-wrapper {
display: table-caption;
caption-side: bottom;
}
<div class='image-container'>
<img src='http://i.imgur.com/nV2qBpe.jpg' class="image">
<div class='text-wrapper'>
<p class='text'>Some text that may need to wrap into multiple lines</p>
</div>
</div>
关于html - 仅使用 css 在图像下自动调整文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185547/