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.
Use
display: table
. This will work in new enough browsers but not in older IE versions.Use
float: left; clear: both
as suggested above. This will work as long as there are no other floats around, and break horribly otherwise.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;
}
精彩评论