开发者

How to make a block element adjust to the size of what is inside it?

If I have this HTML:

<li class="name">hi</li>
<li class="name">hello</li>
<li class="name">wheeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee!</li> 

And this CSS:

li.name{
    border: 1px solid #A38870;
    background-color开发者_JS百科: #FA682D;
    list-style: none;
    margin: 15px;
    padding: 5px;
}

The background extends all the way across the page like this.

How can I make the background adjust to the size of the text like this (without explicitly setting the width for each list element)?


 display: table;

add this css code in li.name css class.


li.name{
  /* your suff */
  float: left;
  clear: both;
}

This so when you float block elements they adapt to the content of the size, the problem is they float left, so they gonna be next to each other, to avoid this you can clear: left or clear: both.


There are several solutions, none really perfect; which one you want depends on your use case.

  1. Use display: table. This will work in new enough browsers but not in older IE versions.

  2. Use float: left; clear: both as suggested above. This will work as long as there are no other floats around, and break horribly otherwise.

  3. Use browser-specific CSS (e.g. Gecko supports width: -moz-fit-content). This has the obvious drawbacks.

For your case and today, display: table probably works best, but going forward we can hope that the fit-content value for width gets standardized.


I think the best way is to use browser-specific CSS, writing a line for each browser like Justin Geeslin explained here :

Is there a css cross-browser value for "width: -moz-fit-content;"?

p{
  width: intrinsic;           /* Safari/WebKit uses a non-standard name */
  width: -moz-max-content;    /* Firefox/Gecko */
  width: -webkit-max-content; /* Chrome */
}


Corrected, working fiddle here: http://jsfiddle.net/ezmilhouse/3jRx7/1/

li.name{
    border: 1px solid #A38870;
    background-color: #FA682D;
    display:inline;
    list-style: none;
    line-height:36px;
    padding:4px;
}

li.name:after { 
    content:"\A";
    white-space:pre;
}


try using clear:both; float: left properties.


Give it display: inline-block

li.name{
    border: 1px solid #A38870;
    background-color: #FA682D;
    list-style: none;
    margin: 15px;
    padding: 5px;

    display: inline-block;

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜