开发者

How can I make my DIV just the size of the text it encloses

I have this code:

<div id="one">
<div i开发者_JAVA百科d="two">my text here</div>
</div>

I have styled the div with id=two and put a box around it. The problem is that it doesn't enclose the text but instead expands to the width of the outer DIV. Is there a way I can make it just size to match the text without specifying width?


You can either

#two {
    display: inline; /* or 'inline-block' */
}

Or:

#two {
    float: left; /* or right */
}

display: inline; stops the div being displayed as a block-level element, causing it to collapse (for want of a better word) to the size of its contents. If you use the alternative display: inline-block then the div retains its ability to have a defined width and height, which may be required for your layout. However it's worth noting that Internet Explorer 6 and 7 only accepts display: inline-block for those elements that are 'naturally inline.'

float has much the same effect; but using float might/will obviously affect the layout of the page, and may need to be cleared by subsequent elements.


display:inline-block;

This way you keep the block behaviour of your div.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜