2016-06-10 111 views
1

我想要在div中输入文字,并在背景中输入字间距和图像。 的我想要实现的一个例子:以字间距和背景图像为中心的文本

Text centered with image inside

她是一个小提琴,显示了我实现迄今:

div { 
 
    width: 200px; 
 
} 
 
h2 { 
 
    display: inline-block; 
 
    text-align: center; 
 
    color: #000000; 
 
    word-spacing: 40px; 
 
    background: url("http://s33.postimg.org/twxfn1by7/Playlist_Triangle.png") top center no-repeat; 
 
    background-size:50px; 
 
    padding: 20px 0; 
 
}
<div> 
 
<h2> 
 
Some text 
 
</h2> 
 
</div>

+0

那么这里有什么问题? –

回答

1

https://jsfiddle.net/wes2sa1t/

你必须把这些单词包装成类似于平底锅让你可以居中。这是如何用CSS做的,因为你用CSS标签标记了这个标签,但你也可以用jQuery来实现。

HTML:

<div> 
<h2> 
<span>Some</span> <span>text</span> 
</h2> 
</div> 

CSS:

h2 { 
    display: inline-block; 
    text-align: center; 
    color: #000000; 
    word-spacing: 40px; 
    background: url("http://s33.postimg.org/twxfn1by7/Playlist_Triangle.png") top center no-repeat; 
    background-size: 50px; 
    padding: 20px 0; 
} 
span { 
    width: 100px; 
    display: inline-block; 
    text-align: right; 
} 
span:nth-child(2) { 
    text-align: left; 
} 
0

而不是居中的东西,它似乎更喜欢你想要的图像字之间间隔均匀。我同意瓦特/布莱恩说,这些词需要在一个范围内包装。我不同意设置固定宽度,因为这是非常有限制的。

相反,我会从H2移动的背景图像,并把它的跨度中的一个伪元素:

h2 { 
    display: inline-block; 
    text-align: center; 
    color: #000000; 
    padding: 20px 0; 
    font-size: 0; // gets rid of whitespace between the spans 
} 

span { 
    font-size: 24px; // resets the font-size of the words 
} 

span:nth-child(1):after { 
    content: ''; 
    display: inline-block; 
    width: 50px; 
    height: 50px; 
    background: url("http://s33.postimg.org/twxfn1by7/Playlist_Triangle.png") top center no-repeat; 
    background-size: 50px; 
} 

使用inline-block的地方都紧挨着对方,并把h2上的font-size:0将删除任何空格。

现在单词可以是任意长度,并且图像将保持完美的间距。

这里有一个演示:https://jsfiddle.net/rq8u5b3k/1/

如果你不能控制无论什么原因,标记,这里有一个jQuery的片段,将在跨度包装的每个单词:

var words = $("h2").text().split(" "); 
$("h2").empty(); 
$.each(words, function(i, v) { 
    $("h2").append($("<span>").text(v)); 
}); 

更新演示:https://jsfiddle.net/rq8u5b3k/3/