user2991837
user2991837

Reputation: 798

Max-width not working on Flexbox item (item is shrinking to width of content)

I have a full viewport width, full viewport height "hero image" on a homepage. I've made this a Flex container. Inside the flex container is one child div (containing a heading). This flex item should be aligned to the bottom of the flex container. It has a max-width and should be horizontally centered inside the parent.

However, the max-width is being ignored. The div is taking the width of its content - the heading. Please see JS Fiddle: https://jsfiddle.net/4h7q6d5x/

As you can see the .main div inside the hero image is taking the width of its content - unlike the .main div below the hero image.

I have looked at various questions, including this one max-width not working on flex item

But adding width:100% to the flex item doesn't work. At smaller viewport sizes the the width and padding don't play nicely and the heading is cropped off the right hand edge.

How do I get max-width to work with Flexbox?

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

.main {
    max-width:500px;
    margin:0 auto;
    padding:0 50px;
    background-color:pink;
    }


<div class="hero_image">
    <div class="main">
        <h1>Heading <br>couple of words</h1>
    </div>
</div>  

<div class="main">
    <p>Lots of content</p>
</div>

Upvotes: 0

Views: 5014

Answers (1)

Paulie_D
Paulie_D

Reputation: 114990

The default "width" (actually flex-basis) inside flex-containers is auto which makes it only as wide as it's content.

But adding width:100% to the flex item doesn't work. At smaller viewport sizes the the width and padding don't play nicely and the heading is cropped off the right hand edge.

Then I'd suggest a couple of changes. Don't use a flex-column but position your .main div using align-items:flex-end.

Then set the default "width" (actually flex-grow) with flex: 1.

.hero_image {
  min-height: 50vh;
  /* for example */
  background-color: yellow;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.main {
  flex: 1;
  max-width: 50%;
  /* for example */
  margin: 0 auto;
  padding: 0 50px;
  background-color: pink;
}
<div class="hero_image">
  <div class="main">
    <h1>Heading <br>couple of words</h1>
  </div>
</div>

<div class="main">
  <p>Lots of text</p>
</div>

Upvotes: 0

Related Questions