CSS width of a <span> tag

Viewed 238699

I use <span> tags in my module titles, e.g.

<span>Categories</span>.

I specify the span's background color/image, width and height in css.

But the span's width depends on its content/text.

So, if I do <span></span>, with just a background image/color in css, nothing appears.

Of course, I want something to appear.

How can I resolve this?

8 Answers

spans default to inline style, which you can't specify the width of.

display: inline-block;

would be a good way, except IE doesn't support it

you can, however, hack a multiple browser solution

You could explicitly set the display property to "block" so it behaves like a block level element, but in that case you should probably just use a div instead.

<span style="display:block; background-color:red; width:100px;"></span>

You can't specify the width of an element with display inline. You could put something in it like a non-breaking space ( ) and then set the padding to give it some more width but you can't control it directly.

You could use display inline-block but that isn't widely supported.

A real hack would be to put an image inside and then set the width of that. Something like a transparent 1 pixel GIF. Not the recommended approach however.

Use the attribute 'display' as in the example:

<span style="background: gray; width: 100px; display:block;">hello</span>
<span style="background: gray; width: 200px; display:block;">world</span>
Related