标签的 CSS 宽度

我在模块标题中使用 <span>标记, 例如:。

<span>Categories</span>.

我用 css 指定跨度的背景颜色/图像、宽度和高度。

但是跨度的宽度取决于它的内容/文本。

因此,如果我使用 <span></span>,只使用 css 中的背景图像/颜色,什么都不会显示。

当然,我希望有东西出现。

我该怎么办?

240456 次浏览

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

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>

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>

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.

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;

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).