1

What I'm attempting to do now, is creating a container (with floated elements) that adapts its width to the elements that fit..

The simplest example I can think of is this: A container is filled with 300px * 300px floating divs. As long as the divs don't fill up a row, the width of the container (cleared both) is the same as the combined width of the divs, or 1 div = 300px, 2 divs = 600px and so on. However, if the divs don't fit on one row, they go on to the next and the width of the container remains at 100% even though the divs on the first row only take up (let's say) 95%.

Is there a pure CSS way of making that container no wider than its contents?

#main {
  float: left;
  background-color: #f00;
}

#main > :last-child:after {
  clear: both;
}

.float {
  width: 150px;
  height: 150px;
  float: left;
  background-color: #00f;
}

<div id="main">
  <div class="float"></div>
  <div class="float"></div>
  <div class="float"></div>
  <div class="float"></div>
  <div class="float"></div>
  <div class="float"></div>
  <div class="float"></div>
  <div class="float"></div>
  <div class="float"></div>
</div>

Here's a JSfiddle: http://jsfiddle.net/j9A6T/ Can you lose the red part to the right?

I have tried using the float/inline-block/table solutions on the container, but they won't work in this case.

LGT
  • 4,957
  • 1
  • 21
  • 22
  • 1
    "Links to jsfiddle.net must be accompanied by code. The code is already at jsfiddle. Shall I paste it here?" Yes, that is exactly what the message means. – Fabrício Matté May 21 '14 at 00:17
  • In case you're wondering, the main point is to don't force answerers into opening an external resource in order to answer a question. That, and your question should hold future meaning even after external links rot. There are so many meta posts about this... – Fabrício Matté May 21 '14 at 00:20
  • So tell them to add this explanation to the red warning box then. The code is not necessary and I had already done a working jsfiddle. This just forced me to add more to the post or remove the link. – LGT May 21 '14 at 00:29
  • I thought the "Links to jsfiddle.net must be accompanied by code" message was simple and good enough, but maybe a link to a meta post might be useful for the interested. Well, you can suggest it at [MSO](http://meta.stackoverflow.com/) anytime (tag it with `feature-request` and/or `discussion`). – Fabrício Matté May 21 '14 at 00:33

1 Answers1

2

Isn't it a case where a clearfix (to apply to your container div) would help?

.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

More here : What is a clearfix?

Community
  • 1
  • 1
Sheraff
  • 5,730
  • 3
  • 28
  • 53