[css] CSS width of a <span> tag

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?

This question is related to css

The answer is


Having fixed the height and width you sholud tell the how to bahave if the text inside it overflows its area. So add in the css

overflow: auto;


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.


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


I would use the padding attribute. This will allow you add a set number of pixels to either side of the element without the element loosing its span qualities:

  • It won't become a block
  • It will float as you expect

This method will only add to the padding however, so if you change the length of the content (from Categories to Tags, for example) the size of the content will change and the overall size of the element will change as well. But if you really want to set a rigid size, you should do as mentioned above and use a div.

See the box model for more details about the box model, content, padding, margin, etc.


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>

Like in other answers, start your span attributes with this:

display:inline-block;  

Now you can use padding more than width:

padding-left:6%;
padding-right:6%;

When you use padding, your color expands to both side (right and left), not just right (like in widht).