Centering text with word spacing and background image

77 Views Asked by At

I'm trying to get a text within div to be entered with word spacing and image in the background. An example of what i'm trying to achieve:

Text centered with image inside

Her's a fiddle that shows what I achieved so far:

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>

2

There are 2 best solutions below

0
On

https://jsfiddle.net/wes2sa1t/

You'd have to wrap the words in something like a span so you can center them. This is how to do it with CSS, as you tagged this with the CSS tag, but you could also achieve this with 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
On

Rather than centering something, it more seems like you want the image evenly spaced between the words. I agree w/ Blaine that the words need to be wrapped in a span. I don't agree with setting a fixed width though, as that is very constraining.

Instead, I would move the background image from the h2 and place it on a psuedo-element of one of the spans:

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;
}

Using inline-block places everything right next to each other, and putting a font-size: 0 on the h2 removes any whitespace.

Now the words can be any length, and the image will remain perfectly spaced between them.

Here's a demo: https://jsfiddle.net/rq8u5b3k/1/

If you can't control the markup for whatever reason, here's a jQuery snippet that will wrap each word in a span:

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

Updated demo: https://jsfiddle.net/rq8u5b3k/3/