Francisco Romero
Francisco Romero

Reputation: 13199

How to vertically wrap content with flexbox?

I have three divs inside a flexbox container.

I would like the three divs to be displayed as follows:

+-----------------------------------------------+
|     +-----------------+-----------------+     |
|     |                 |                 |     |
|     |                 |                 |     |
|     +-----------------+-----------------+     |
|                                               |
|     +-----------------------------------+     |
|     |                                   |     |
|     |                                   |     |
|     +-----------------------------------+     |
|                                               |
+-----------------------------------------------+

so the container will have to adapt vertically to its content but only to its content, not more than that.

I am getting big white spaces between the divs and the container is getting the 100% of the height of its parent, though.

I tried without putting height property to the container and setting height: auto; but neither of them worked.

Here is the code I have:

*{
   box-sizing: border-box;
}

html,body{
   width: 100%;
   margin: 0;
}

#container{
	display: flex;
	position: absolute;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	margin: auto;
	justify-content: center;
	align-items: center;
	flex-wrap: wrap;
	max-width: 450px;
	border: 1px solid;
}

#div1{
	width: 50%;
	height: 155px;
	background-color: blue;
}

#div2{
    width: 50%;
    height: 155px;  
    background-color: red;
}

#div3{
    width: 70%;
    height: 155px;
    background-color: green;
}
<div id="container">
  <div id="div1"></div>
  <div id="div2"></div>
  <div id="div3"></div>
</div>

Note: Make it bigger to see the white spaces between the divs.

How can I make the container shrink-wrap the content and not be 100% height of its parent?

Thanks in advance!

Upvotes: 3

Views: 8152

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 372174

When you create a flex container, an initial setting is align-content: stretch.

This causes multiple lines of flex items to distribute themselves across the full length of the container.

Override this setting with align-content: flex-start on #container.


To make the #container shrink-wrap its contents vertically, you need to remove this rule:

#container { bottom: 0; }

Because #container is absolutely positioned, and there is no parent element that is positioned, which would establish the containing block for #container, the default containing block becomes the initial containing block or, the viewport.

That's why the container is stretching from top to bottom, as illustrated by the black border you applied. Once your remove bottom: 0 the container will act more like height: auto.

Learn more about CSS positioning here: https://developer.mozilla.org/en-US/docs/Web/CSS/position

Upvotes: 2

Related Questions