2014-09-19 62 views

回答

2

<div>默认为display: block,这意味着它将占用全角。如果您希望它只占用其内容的空间,则可以尝试使用inline-block

然后,如果您只希望<div>拉伸至 X像素,则可以使用max-width

div { 
 
    display: inline-block; 
 
    max-width: 200px; 
 
    background-color: blue; /* for illustration only */ 
 
}
<div>short content</div> 
 
<div>longer content here longer content here longer content here longer content here longer content here longer content here longer content here </div>

正如你所知道的,这也把旁边的海誓山盟的div。

1

听起来像是你正在寻找的CSS属性最小宽度

min-width:200px; 
width:auto; 

对不起,也许我读问题不对。

max-width:200px; 
display:inline-block; //xec is correct inline-block instead of display block lets it adjust from 0-max-width. I was missing that piece until he posted his answer. His is correct. 

这将采取文本并将其包装在200px宽,但容器将从0 px扩展到200px。如果它不以这种方式行事,那么你可能有其他的CSS造成问题。

+0

nope。如果内容小于200px,我希望宽度是内容宽度,而不是200px。 – NotGaeL 2014-09-19 15:44:17

+2

然后使用'max-width'来代替。 – 2014-09-19 15:44:26

+0

它会更像'max-width:200;宽度:自动;'。但在这种情况下,内容会在达到200px之前被打包。我不知道为什么... – NotGaeL 2014-09-19 15:45:12