html - 仅使用 css 在图像下自动调整文本

标签 html css word-wrap

我试图在图像下布置一些文本,图像决定容器的宽度,文本换行成几行以适应宽度。

我当前的代码如下所示:

.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/

相关文章:

html - 如何从 HTML 中的链接中删除下划线?

javascript - 使用 JavaScript 将输入字段循环到每个表列中

html - Heroku 搞乱了我的 CSS 定位。在本地主机上看起来不错,在 Heroku 上看起来很糟糕

html - 如何在 CSS 中正确设置宽度 - 需要修复 Mac 和 iPad 上 Safari 的错误

iphone - 如何创建一个自动换行文本的 UITextView?

html - 尽管缺少文本,但仍强制垂直对齐?

javascript - 光标与文本不对齐

html - 在 IE11 中 Bootstrap 导航栏搜索拆分

c - 在 valgrind 中包装函数时断言失败

html - 防止空格与单词换行