4

I have a container div with a few elements inside, like so:

<div class="container">
  <p>one</p>
  <p>two</p>
  <p>three</p>
  <p>four</p>
  <p>five</p>
  <p>six</p>
  <p>seven</p>
  <p>eight</p>
</div>

It looks like this:

SS

You can the that the .container div (in blue) extends to fill the whole width of the window. I would like it to always 'hug' the p's inside, to always have the minimum width necessary.

I have accomplished by setting it to display: inline-block. Now it looks like SS2

Here comes the problem. When I re-size the window so that one of the elements gets 'pushed' down to a second row, the .container div does not shrink to fit the new size of the elements. Instead, it stretches to the edge of the window.

SS3

How would I make the div fit its contents, even when re-sizing, so that it would look like so?

SS4

I have searched and searched, but could not find an answer to this problem.

JSFiddle Here

dippas
  • 58,591
  • 15
  • 114
  • 126
Manu
  • 319
  • 1
  • 3
  • 11
  • Check out Flexbox https://css-tricks.com/snippets/css/a-guide-to-flexbox/ – erikvimz May 23 '16 at 17:19
  • Duplicate of [CSS when inline-block elements line-break, parent wrapper does not fit new width](http://stackoverflow.com/q/34995740/1529630). Not possible. – Oriol May 23 '16 at 17:35

1 Answers1

2

That's not possible, so as close as possible, you can use flexbox for that

body {
  margin: 0
}
.container {
  background: lightblue;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap
}
.container p {
  background: pink;
  font-size: 40px;
  margin:10px 0
}
<div class="container">
  <p>one</p>
  <p>two</p>
  <p>three</p>
  <p>four</p>
  <p>five</p>
  <p>six</p>
  <p>seven</p>
  <p>eight</p>
  <p>nine</p>
  <p>ten</p>
</div>
dippas
  • 58,591
  • 15
  • 114
  • 126
  • You are only justifying the items, not shrinking the container, which I don't think is possible. – Oriol May 23 '16 at 17:33
  • @Oriol, Ya I don't think so too, but this what I remember to get as close as possible of what OP is trying to achieve – dippas May 23 '16 at 17:36