问题
I'm trying to lay out some text under an image in such a way that the image determines the width of the container and the text wraps into several lines to fit the width.
My current code looks like this:
.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>
But as you can see, since the text is positioned with absolute, it isn't part of the container height, making it impossible to correctly layout on the rest of my page.
How do I solve this correctly? I'd rather lose some browser compatibility than use js btw.
回答1:
Try this
.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>
Here is another solution you could try
.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>
来源:https://stackoverflow.com/questions/34185547/autofit-text-under-image-with-only-css