2

I have a span with a background image, but it aligns differently without text in it, how can i have them aligned independent of the content?

For this it has to be inline-block and it has to be a css only solution.

Here is an example.

HTML:

Test
<span class="test">Blafffff</span>
<span class="test"></span>

CSS:

.test
{
    display: inline-block;
    line-height: 30px;
    border: none;
    height: 30px;
    width: 120px;
    text-align: center;
    margin-top: -15px;
    background: url("http://i.imgur.com/vYiCjoF.png") no-repeat;
}

EDIT: Thanks for the answers so far, but it has to align with the other text around it, i updated the example

John Smith
  • 374
  • 2
  • 11

3 Answers3

2

You are using display: inline-block; so the span will align to the baseline, hence use vertical-align: top; to align them consistently.

Demo

.test {
    /* Other properties */
    vertical-align: top;
}

Alternatively, you can also use float: left; here, than you won't need vertical-align property, but than you need to make sure that you clear the floating elements.


For more information on float and clear, you can refer my answer here and here.

Community
  • 1
  • 1
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
  • Thanks, but now it doesn't align with the other text around it, i updated the example. – John Smith Jan 27 '14 at 07:32
  • @JohnSmith : remove `margin-top: -15px;` because that is causing the problem in alignment => http://jsfiddle.net/9YUdb/4/ – NoobEditor Jan 27 '14 at 07:35
  • @NoobEditor I removed that and made it more standard – Mr. Alien Jan 27 '14 at 07:35
  • @Mr.Alien : wrapping in another `div` with `line-height` will cause probs if there is more than 1 line of text!! :p – NoobEditor Jan 27 '14 at 07:36
  • @NoobEditor Well, yes, but here it doesn't seem that he has more than one line.. if not than obviously the negative margin should be removed – Mr. Alien Jan 27 '14 at 07:36
  • @Mr.Alien : your solution goes with assumption that there isn't more than 1 line of text, my assumption goes opposite...let OP decide what he wants...we gave 2 solutions..job done!! :) – NoobEditor Jan 27 '14 at 07:39
0

http://jsfiddle.net/9YUdb/2/

.test
{
    display: inline-block;
    float: left;

}
CRABOLO
  • 8,605
  • 39
  • 41
  • 68
0

To align with the text around it, you'll need to give the span some content. You can do that with a :before pseudo-element. Putting it a zero-width non-breaking space will do the trick. i.e.

.test:before {
    content: '\FEFF';
}

See http://jsfiddle.net/9YUdb/6/

Alohci
  • 78,296
  • 16
  • 112
  • 156