1

我正在尝试在 div 中输入要在背景中输入字间距和图像的文本。我试图实现的一个例子:

以图片为中心的文本

她的小提琴展示了我到目前为止所取得的成就:

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>

4

2 回答 2

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;
}
于 2016-06-10T01:15:39.447 回答
0

与其将某些东西居中,不如说您希望图像在单词之间均匀分布。我同意 Blaine 的说法,这些词需要包含在一个跨度中。不过,我不同意设置固定宽度,因为这非常受限制。

相反,我会从 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/

于 2016-06-10T02:20:19.090 回答