Autofit text under image with only css

北城余情 提交于 2020-02-06 05:08:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!