根据图像宽度拟合文本

时间:2013-10-02 04:29:40

标签: html css

图像尺寸可能会有所不同,但文字下方不应超出演示的图像宽度

HTML

<img />
<p>some text</p>

+----------------------------+
|                            |
|                            |
|       image                |
|                            |
|                            |
|                            |
+----------------------------+
The result should not be this because overflowing the image width

从右

+----------------------------+
|                            |
|                            |
|       image                |
|                            |
|                            |
|                            |
+----------------------------+
The result should be this 
because its not overflowing 
the image width

现在如果我的图像更大,那么这应该是这样的

+------------------------------------------------------+
|                                                      |
|                                                      |
|                                                      |
|                                                      |
|                                                      |
|                                                      |
|        image                                         |
|                                                      |
|                                                      |
|                                                      |
|                                                      |
|                                                      |
+------------------------------------------------------+
The result should be this because its not overflowing 
the image width

有什么想法吗?我该如何标记或给出风格?

2 个答案:

答案 0 :(得分:1)

使用css tables并将表格的宽度设置得非常小。

<强> WORKING FIDDLE

<div>
  <img />
  <p>some text</p>
</div>

CSS

div
{
    display: table;
    width: 1px;
}
img, p
{
    display: table-row;
}

答案 1 :(得分:0)

除非你使用js。在某些时候,如果你想让它显示全部比例,你将需要知道图像的尺寸。如果您不介意用css控制宽度和高度,可以执行此操作fiddle

#f {
    background:url('http://jquery.malsup.com/cycle2/images/beach1.jpg') no-repeat top left;
    height:200px;
    width:200px;
    border:1px solid blue;
    vertical-align:text-bottom;
}
#content{
    position:relative;
    bottom:-100%;
    border:1px solid red;
}

<div id="f">
    <p id="content">
    Sets the width and height of the background image. The first value sets the width, the second value sets the height. If only one value is given, the second is set to "auto"
    </p>
</div>

并不能真正回答你的问题,但是应该让你知道为什么只用css2很难,我知道css3知之甚少,也许可以用css3来完成