Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show background of empty span

Tags:

Let's say that I have a span and I set an image as the background of the span like this:

<span style="background:url("my_image.png") no-repeat;"></span>

As you can see above, my span is empty. If I put some content in my span like:

<span style="background:url("my_image.png") no-repeat;">Some content...</span>

I can see the background image of the span with no problem. But If I leave the span empty I don't see the background image. I figured that I could solve this issue by adding some padding to my span like:

<span style="background:url("my_image.png") no-repeat;padding:20px;"></span>

But is there another way I can do this without adding some padding to my span and keep my span empty?

Thank you

like image 390
user765368 Avatar asked May 24 '13 21:05

user765368


People also ask

Can a span be an image?

Usually span element is used to group inline elements together to implement style (using id or class attributes) or language information or JavaScript DOM(using id or class attributes), when no other element is found suitable to form that group. 3. The element can contain a piece of text or an image directly.

Is span an Htmlelement?

<span>: The Content Span elementThe <span> HTML element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang .

Can we use span inside paragraph?

The HTML span element is an inline element, which means that it can be used inside a block element and not create a new line. If you ever want to highlight some text inside a paragraph, wrap that text in a span tag and give it a class.


2 Answers

You get the same effect by using inline-block but setting width and height instead of using padding.

<span style="background:url('my_image.png') no-repeat; display: inline-block; width: 40px; height: 40px;"></span>

Also, something else that could trip you up is you are using double-quotes inside of an HTML attribute, which would confuse a parser and could lead to unexpected results. I've changed them to single quotes in the code I posted above, although no quotes would do just as well.

like image 53
Alyssa Ross Avatar answered Sep 20 '22 15:09

Alyssa Ross


just don't make it empty: put a 'blank' inside. There are three ways, to do that:

  1. simple space and add style white-space: pre; to it

  2. Non-breaking Space &nbsp; or &#160;

  3. The non plus ultra is, to let css do the trick for you:

add this style to your span:

 :before {
    content: "\200D";
    display:inline;
 }  

What happens:

you add a content before (or better "in front inside") your span, that displays a ZERO WIDTH JOINER, and your span is not empty enymore

like image 33
halfbit Avatar answered Sep 17 '22 15:09

halfbit