单个文本行的背景宽度

时间:2013-07-26 02:07:42

标签: html css

基本上我想要做的是,考虑下面的例子,根据文本大小创建一个流畅的动态背景宽度,多行。这是因为我设置了一个对齐的文本对齐方式,并且在某些时候(例如在第二行),文本没有填满背景的所有宽度,后者由较大的上部句子放大。我不希望背景填满它!我不知道我是否清楚自己,但我会尝试用下面的例子来解释。

http://jsfiddle.net/gcAhL/

HTML

<div class="image">
    <img src="http://s23.postimg.org/g033nno17/image.jpg">
    <div class="title">This is a title</div>    
</div>
<div class="image">
    <img src="http://s23.postimg.org/g033nno17/image.jpg">
    <div class="title">This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title</div>    
</div>

CSS

.image {
    position: relative;
    width: 800px;
    height: 530px;
    margin: 10px;
}
.title {
    position: absolute;
    background-color: #CCC;
    text-align: justify;
    max-width: 600px;
    bottom: 30px;
    padding: 5px;       
}

如您所见,最后一个蓝色方块的文字分为两行。灰色背景填充宽度基于第一行。我想要发生的是,在第二行中,灰色仅填充该行的文本。

示例:http://s9.postimg.org/634pzc9y7/example.jpg

这甚至可能吗?提前感谢所有回复。

1 个答案:

答案 0 :(得分:1)

只需在<span>内使用<div>元素,并为<span>元素而不是<div>提供背景颜色。

<强> HTML

<div class="image">
    <img src="http://s23.postimg.org/g033nno17/image.jpg">
    <div class="title"><span>This is a title</span></div>    
</div>
<div class="image">
    <img src="http://s23.postimg.org/g033nno17/image.jpg">
        <div class="title"><span>This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title This is a title</span></div>    
</div>

<强> CSS

.image {
    position: relative;
    width: 800px;
    height: 530px;
    margin: 10px;
}
span{background-color: #CCC;}
.title {
    position: absolute;
    line-height:100%;
    text-align: justify;
    max-width: 600px;
    bottom: 30px;
    padding: 5px;       
}