Jonas Sourlier
Jonas Sourlier

Reputation: 14435

How to achieve `min-height: content` on a flex container?

I have a vertical flex container that centers its content. The height of the container should depend on the viewport height, such that the flexed content appears vertically centered. However, the container height should never be smaller than the content's, otherwise the top of the content would flow out of the viewport's top.

In other words:

However, this does not seem to work:

    .flex-container {
        display: flex;
        flex-direction: column;
        height: 100vh;
        justify-content: center;
    }
        .flex-item {
            flex: 0 0 auto;
        }
             .content {
                 background-color: red;
                 font-size: 50px;
                 color: white;
                 height: 115vh;
             }
<div class="flex-container">
    <div class="flex-item">
        <div class="content">
            Content
        </div>
    </div>
</div>

As you can see, the content starts to disappear as soon as we set .content's height to something higher than 100vh.

Note that I can't set a fixed min-height on .flex-container since I don't know the content's height beforehand.

How to achieve that?

Upvotes: 14

Views: 17828

Answers (1)

fen1x
fen1x

Reputation: 5880

You can set

.flex-container {
    height: auto;
    min-height: 100vh;
}

That way if height of content is less than 100vh - container's height will be 100vh (from min-height:100vh;).

html,body {
  margin: 0;
}
.flex-container {
  display: flex;
  flex-direction: column;
  height: auto;
  min-height: 100vh;
  justify-content: center;
}

.flex-item {
  flex: 0 0 auto;
}

.content {
  background-color: red;
  font-size: 50px;
  color: white;
  height: 25vh;
}
<div class="flex-container">
  <div class="flex-item">
    <div class="content">
      Content
    </div>
  </div>
</div>

If height of content is more than 100vh - container's height will be height of it's content (from height:auto;).

html,body {
  margin: 0;
}
.flex-container {
  display: flex;
  flex-direction: column;
  height: auto;
  min-height: 100vh;
  justify-content: center;
}

.flex-item {
  flex: 0 0 auto;
}

.content {
  background-color: red;
  font-size: 50px;
  color: white;
  height: 115vh;
}
<div class="flex-container">
  <div class="flex-item">
    <div class="content">
      Content
    </div>
  </div>
</div>


EDIT: Since you also need max-height for your content, you can add next media query in the end:

@media (min-height: 1800px) {
  .content {
    height: 1800px;
  }
}

It will force height of .content to be 1800px on displays with height >= 1800px

Upvotes: 12

Related Questions