Robert Leggett
Robert Leggett

Reputation: 982

What is the difference between the flex and height properties?

Given the following example, both will fill out the center to consume the remaining space in the page, given the page is using flex. I am leaning towards using the css property flex vs height in the body. Is there a difference that needs to be considered when applying one over the other?

CSS

.page {
  display: flex;
  flex-direction: column;
}

.header {
  height: 100px;
}

.body {
  flex: 1; // vs height: 100%;
}

.footer {
  height: 40px;
}

HTML

<div class="page">
   <div class="header">Sample Header</div>
   <div class="body">Sample Body</div>
   <div class="footer">Sample Footer</div>
</div>

Upvotes: 3

Views: 1551

Answers (3)

Michael Benjamin
Michael Benjamin

Reputation: 371719

When you set an element to flex: 1, that breaks down to:

  • flex-grow: 1
  • flex-shrink: 1
  • flex-basis: 0

In a column-direction container (like you have), the flex properties above apply vertically. This means that flex-basis and height are equivalent properties.

flex-basis = height (in a column-direction container)

There is an obvious difference between flex-basis: 0 and height: 100%. It's the same difference as height: 0 and height: 100%.

In your situation, where there is a .header and a .footer consuming 140px of vertical space, setting the middle item (.body) to height: 100% would normally cause an overflow.

But since an initial value of a flex container is flex-shrink: 1, flex items are permitted to shrink, and this wouldn't happen. However, it's still sloppy and imprecise coding, in my view.

By setting .body to flex: 1, you're setting the height to 0, but also allowing it to consume free height with flex-grow: 1. I would say, in this case, that this solution is more efficient.


More details:

Upvotes: 2

PPL
PPL

Reputation: 6565

Try below code

.page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.header {
  height: 100px;
   display: flex;
  align-items: center;
  justify-content: center;
}

.body {
    display: flex;
  flex-direction:  column;
    height: 80vh;    
      align-items: center;
  justify-content: center;  

}

.footer {
  height: 40px;
    display: flex;
     align-items: center;
  justify-content: center;
}
<div class="page">
   <div class="header">Sample Header</div>
   <div class="body">Sample Body</div>
   <div class="footer">Sample Footer</div>
</div>

Upvotes: 0

Amerrnath
Amerrnath

Reputation: 2417

There is a huge difference between flex and height.

First to answer your question.

  1. Height 100% doesn't use the remaining space. It will use all the spaces of parent, in your case if page dom is height 200px; then body will also be height: 200px;.

  2. Flex will be correct solution here to fill up the space (flex: 1).

    Flex is more than filling the space, its more of a layout and it has influences on its child, how they position and align.

Upvotes: 3

Related Questions