Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max-width not working on flex item

Tags:

html

css

flexbox

I have a flex container and two flex children in a column. The top div should fill all remaining space. The bottom div should have a height determined by the content and a max-width. But the bottom div's width is shrinking to the width of its content. The max-width is being ignored.

.hero_image {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: yellow;
}

.impact_image {
  flex-grow: 1;
  background-image: url(https://s16.postimg.org/cjw1kzkkl/circles.png);
  background-position: center bottom;
  background-size: cover;
}

.intro {
  max-width: 600px;
  flex-shrink: 0;
  margin: 0 auto;
  background-color: pink;
}

h1 {
  font-size: 20px;
}
<div class="hero_image">
  <div class="impact_image"></div>
  <div class="intro">
    <h1>XYZ brand consultancy<br>making a difference</h1>
  </div>
</div>

Here is the JS Fiddle: https://jsfiddle.net/cke6qr8e/

like image 903
Markeee Avatar asked Apr 30 '17 11:04

Markeee


1 Answers

Flex items, by default, may shrink to their content size. (This behavior may vary among browsers.)

This is because flex items no longer exist in a block formatting context, where block level elements automatically take width: 100%. In a flex formatting context, elements have different defaults.

Therefore, to get max-width to work on a flex item, also give the item width: 100%.

.hero_image {
	min-height:100vh;
	display:flex;
	flex-direction:column;
  background-color:yellow;
	}

.impact_image {
	flex-grow:1;
	background-image:url(https://s16.postimg.org/cjw1kzkkl/circles.png);
	background-position: center bottom;
	background-size:cover;
	}
  
  .intro {
	max-width:600px;
	flex-shrink: 0;
  margin:0 auto;
  background-color:pink;
  width: 100%; /* NEW */
	}

h1 {
	font-size:20px;
	}
<div class="hero_image">
	<div class="impact_image"></div>
	<div class="intro">	
		<h1>XYZ brand consultancy<br>making a difference</h1>
	</div>
</div>
like image 152
Michael Benjamin Avatar answered Nov 07 '22 23:11

Michael Benjamin