Alex Rivera | Logout

CSS div as wide as its contents

Asked 2011-08-10T17:24:56.457
12

I'm still very much a CSS novice. For many years I've managed my layout using nested tables, which I know all CSS people would tell me is evil. I've piddled around with CSS for many years, but ever since the beginning I've been unable to make it control my layout the way I want it to.

In short, what I want is to have a <div> that will only be as wide as its contents. I do not want to set its size. I want it to be only as wide as its contents, which is created dynamically.

A table does this perfectly. With a <div> it always seems to do something other than what I want. No "overflow" option does what I want.

The classic example is when I want to create a full-page columnar layout with the left column containing navigation links and the right side containing the content. I want the left column to be precisely as wide as the navigation links. No more, no less. (The navigation links are not static; they're created dynamically and could change in size/length at any time). And the right ("content") column should be whatever's left over. Most importantly, when I make the browser screen wider or narrower, I want left column to STILL be exactly as wide as the nav-links: no more, no less. I want the contents to automatically wrap as needed, if the browser's width gets too narrow. Under no circumstances do I want the text to be obscured or to go outside of the defined column.

In short, I want a <div> that works as well as a table without having to use a table. Surely, CSS experts. this can be done....right? I've asked this question in other forums, and have never yet received an acceptable answer.

Or take a somewhat-related simple example like this (perhaps this one is easy):

<ul style="background: orange;">
   <li>one</li>
   <li>two</li>
   <li>three</li>
</ul>

The entire thing is as wide as the browser screen. But I wa

Edit
Report

2 Answers

3

Use a <span> and display: inline-block.

answered 2011-08-10T17:26:51.687
1

Set display: inline-block on the containing div.

Example: http://jsfiddle.net/bVRVb/

What's happening is that divs by default are display: block, which means they will take up as much horizontal space as is available, and make everything else around them appear above or below them. With inline-block, they still have a fixed form, but will appear inline next to things around them, and take up only as much space as they need.

Here is a more comprehensive look at block vs inline-block.

answered 2011-08-10T17:30:19.877

Your Answer