如何为 SPAN 设置高度属性

我需要使以下代码与预定义的高度可伸缩

<style>
.title{
background: url(bg.gif) no-repeat bottom right;
height: 25px;
}
</style>


<span class="title">This is title</span>

但是因为 跨度是内联元素,所以“ height”属性不起作用。

我尝试使用 Div代替,但它将扩展到上面的元素的宽度。宽度要灵活。

有人能提出解决这个问题的好办法吗?

先谢谢你。

168987 次浏览

Why do you need a span in this case? If you want to style the height could you just use a div? You might try a div with display: inline, although that might have the same issue since you'd in effect be doing the same thing as a span.

Give it a display:inline-block in CSS - that should let it do what you want.
In terms of compatibility: IE6/7 will work with this, as quirks mode suggests:

IE 6/7 accepts the value only on elements with a natural display: inline.

Use

.title{
display: inline-block;
height: 25px;
}

The only trick is browser support. Check if your list of supported browsers handles inline-block here.

Assuming you don't want to make it a block element, then you might try:

.title  {
display: inline-block; /* which allows you to set the height/width; but this isn't cross-browser, particularly as regards IE < 7 */
line-height: 2em; /* or */
padding-top: 1em;
padding-bottom: 1em;
}

But the easiest solution is to simply treat the .title as a block-level element, and using the appropriate heading tags <h1> through <h6>.

this is to make display:inline-block work in all browsers:

Quirkly enough, in IE (6/7) , if you trigger hasLayout with "zoom:1" and then set the display to inline, it behaves as an inline block.

.inline-block {
display: inline-block;
zoom: 1;
*display: inline;
}

span { display: table-cell; height: (your-height + px); vertical-align: middle; }

For spans to work like a table-cell (or any other element, for that matter), height must be specified. I've given spans a height, and they work just fine--but you must add height to get them to do what you want.

Another option of course is to use Javascript (Jquery here):

$('.box1,.box2').each(function(){
$(this).height($(this).parent().height());
})

In some case you may want to adjust a SPAN height without changing display : inline.

To solve this, you can add a top and/or bottom border property, setting the required width parameter to your needs, and a transparent color to hide that border :

.myspan {
border-top : solid 3px transparent;
border-bottom : solid 3px transparent;
}
.my-span {
border: solid 1px;
border-color: gray;
border-radius: 6px;
padding-left: 5px;
padding-right: 5px;
height: 17px;
padding-top: 6px;
display: inline-block;
line-height: 0px;
}

enter image description here