April 6, 2012

Placing an icon beside the text of an H1 tag by using a span

Question by Only Bolivian Here

Here’s the HTML I’m trying to use:

<h1>Order Not Paid<span class="not-paid"></span></h1>

Of course if there is a better way please say so.

Currently since there is no text inside of the span, it seems the browsers are ignoring this tag. Firebug shows up grayed out when inspecting.

When I place text in the span, the icon shows correctly.

What CSS rule can I apply for this effect? Here’s what I have so far (It’s SASS, but easy to grasp):

h1 {
    font-size: 24px;

    span.not-paid {
        background-image: url('/Public/images/remove.png');
        background-repeat: no-repeat;
    }
}

I’d like the icon to appear where the span is.

Alternatively, is it kosher to do something like this? If so, I can settle with this as it looks good on IE8 and modern browsers.

<h1>Order Not Paid <img src="@Url.Content("~/Public/images/remove.png")" alt="" /></h1>

Answer by Alex

If the icon is small and not reused anywhere else just set it as part of the h1.

HTML:

<h1 class="not-paid">Order Not Paid</h1>

CSS:

h1.not-paid {
  font-size: 24px;
  padding:0 16px 0 0; /* whatever the dimensions the image needs */
  background-image: url('/Public/images/remove.png') no-repeat right center; /* Position left/right/whatever */
}

A little cleaner this way.

Answer by Starx

First, if you are not using sass and less, your stylesheet is wrong. Next, give inner-block to span and the image height and width.

h1 {
    font- size: 24px;
}

h1 span.not-paid {
    width: 50px;
    height: 50px;
    display: inline-block;
    background-image: url('/Public/images/remove.png');
    background-repeat: no-repeat;
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!