pennydrops
pennydrops

Reputation: 149

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

If I have this code:

li.name{
    border: 1px solid #A38870;
    background-color: #FA682D;
    list-style: none;
    margin: 15px;
    padding: 5px;
}
<li class="name">hi</li>
<li class="name">hello</li>
<li class="name">wheeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee!</li> 

The background extends all the way across the page.

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

Upvotes: 13

Views: 15357

Answers (7)

J.Delannoy
J.Delannoy

Reputation: 375

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 */
}

Upvotes: 1

meo
meo

Reputation: 31259

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.

Upvotes: 2

Usman Ali
Usman Ali

Reputation: 1312

 display: table;

add this css code in li.name css class.

Upvotes: 13

Boris Zbarsky
Boris Zbarsky

Reputation: 35084

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.

Upvotes: 1

Anji
Anji

Reputation: 723

try using clear:both; float: left properties.

Upvotes: 0

ezmilhouse
ezmilhouse

Reputation: 9131

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;
}

Upvotes: 0

Bazzz
Bazzz

Reputation: 26942

Give it display: inline-block

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

    display: inline-block;

}

Upvotes: -2

Related Questions