1

In my application I have tags that can be from 5 to 15 characters. By that reason the tags width differ, but the surrounding divs increases with the parents width, not the content.

What should I put in the CSS to make the divs width adapt to the width of it's content?

Thanks in advance!

HTML

<div class="tag">
    <a href="#">
        <span class="content">Test album</span>
    </a>
    <a href="#" class="album">X</a>
</div>

CSS

div.tag {
    background: red;
}

Test case: http://jsfiddle.net/T4XJ3/1/

holyredbeard
  • 19,619
  • 32
  • 105
  • 171
  • Make sure the div doesn't get given a width from another rule applied to it non-directly. Also make sure it's parents are also not given an explicit width. A tool like Chrome's inspector or Firebug is indispensable here. – Bojangles May 22 '12 at 23:02
  • 2
    A [test case](http://jsfiddle.net/) would make your question easier to answer. – thirtydot May 22 '12 at 23:03
  • possible duplicate of [Make CSS Div Width Equal To Contents](http://stackoverflow.com/questions/450903/make-css-div-width-equal-to-contents) – Neil May 22 '12 at 23:09

2 Answers2

2

The <div> element has display:block, so it will always take the full width of their container.

You can make them "flexible" by using display: inline-block (demo).

Is this what you're looking for?

Zuul
  • 16,217
  • 6
  • 61
  • 88
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
2

inline-block to the rescue!

div.tag {
  background: red;
  display: inline-block;
}

From the w3c spec:

This value causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.

In simpler terms this means that outside of your div it acts like a span would (sizes to fit contents, flows inline in content, etc.), and inside of your div it acts like a div normally would (for positioning, sizing, padding, etc.).

Kevin Vaughan
  • 14,320
  • 4
  • 29
  • 22