仅使用 css 自动调整图像下的文本 [英] Autofit text under image with only css

查看:31
本文介绍了仅使用 css 自动调整图像下的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在图像下布置一些文本,使图像确定容器的宽度,并且文本换行成多行以适应宽度.

我当前的代码如下所示:

.image-container {显示:内联块;文本对齐:居中;填充:6px;背景颜色:红色;/* 突出显示容器大小 */}.图片 {高度:120px;}.text-wrapper {位置:相对;宽度:100%;}.文本 {位置:绝对;左:0px;顶部:100%;右:0px;}

<img src='http://i.imgur.com/nV2qBpe.jpg' class="image"><div class='text-wrapper'><p class='text'>一些可能需要换行成多行的文本</p>

但是正如您所看到的,由于文本是绝对定位的,它不是容器高度的一部分,因此无法在我页面的其余部分正确布局.

我该如何正确解决这个问题?顺便说一句,我宁愿失去一些浏览器兼容性也不愿使用 js.

解决方案

试试这个

.image-container {显示:表;宽度:1%;}图像{高度:120px;}.文本 {溢出:隐藏;}

<img src='http://i.imgur.com/nV2qBpe.jpg' class="image"><div class='text-wrapper'><p class='text'>一些可能需要换行成多行的文本</p>

这是您可以尝试的另一种解决方案

.image-container {显示:表;}图像{高度:120px;}.text-wrapper {显示:表格标题;字幕侧:底部;}

<img src='http://i.imgur.com/nV2qBpe.jpg' class="image"><div class='text-wrapper'><p class='text'>一些可能需要换行成多行的文本</p>

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.

解决方案

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>

这篇关于仅使用 css 自动调整图像下的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆