希望文本包含在div中

时间:2013-12-19 07:51:40

标签: html word-wrap css

在下面的代码中,我有3张图片,图片下面有一些标题。我不希望文本的宽度超过图像的宽度。注意:图像的宽度可能会有所不同。它不是固定宽度。如果文本超出图像的宽度,则文本需要换行。我在下面的代码中遇到的另一个问题是第二个和第三个图像在图像的底部显示了一些填充。此图像周围的边框应该没有填充。

http://jsfiddle.net/AndroidDev/Asu7V/15/

<div style="width:300px; overflow-x: auto;white-space: nowrap;">
    <div style="vertical-align:top">
        <div class="x">
            <img src="http://25.media.tumblr.com/avatar_dae559818d30_128.png" />
            <div style="white-space:wrap">Grumpy Cat is a famous cat</div>
        </div>
        <div class="x">
            <img src="http://scottsdalepethotel.com/wp-content/uploads/et_temp/cat-648150_128x128.jpg" />
            <img src="http://playgo.ro/wp-content/themes/play3.0/play.png" style="position:absolute; left:0; top:0" />
        </div>
        <div class="x">
            <img src="http://blog.sureflap.com/wp-content/uploads/2011/11/Maru.jpg" />
        </div>
    </div>
</div>

3 个答案:

答案 0 :(得分:1)

由于您没有为width元素分配任何div,因此请分配,而不是使用white-space: normal;

<div style="white-space: normal; width: 130px;">Grumpy Cat is a famous cat</div>

Demo

再一次,我想警告你避免使用内联样式..

此外,当您修复仅包含图片的包装div时,最好为max-width使用max-heightimg,这样可以确保赢得't overflow

此外,最后但并非最不重要,请考虑使用p元素而不是div,这将为您的文字提供一些语义含义。


您使用white-space: wrap; wrap不是white-space属性的有效值,因此您需要normal


正如您评论的那样,您希望摆脱任何一方的空白区域,因此,通过为包装器元素指定一些固定的width以及为图像问题下方的空白区域修复包装器元素,可以通过在包装器元素上使用font-size: 0;而不是为文本分配一些font-size来修复,或者更好的方法是使用display: block;作为img元件。

答案 1 :(得分:0)

你的css缺少宽度,这是一个演示: DEMO

<强> HTML

<div style=""><span class="text">Grumpy Cat is a famous cat</span>

<强> CSS

 .text {
        vertical-align:top;
        display:inline-block;
        white-space:normal;
        word-wrap: break-word;
        width:70%;
        max-width:70%;
    }
    .x {
        border:1px solid #000000;
        display:inline-block;
        white-space:nowrap;
        position:relative;
        width:42%;
        vertical-align: top;
    }

答案 2 :(得分:0)

一种简单的方法是将图像和文本包装在一个div中,这样当图像大小增加时,它也会为文本提供相同的区域,也不会超出图像范围。