skip to Main Content

I’m trying to create a simple layout using CSS Flexbox, but I’m running into an issue where my flex item is not taking up the full height of its parent container. Here’s my code:

.container {
  display: flex;
  flex-direction: column;
  height: 300px;
  background-color: #f0f0f0;
  padding: 20px;
}

.item {
  background-color: #fff;
  padding: 20px;
  border: 1px solid #ddd;
}
<div class="container">
  <div class="item">This is my flex item</div>
</div>

In this example, I would expect the .item element to take up the full height of the .container element, but instead it only takes up the height of its content. I’ve tried setting height: 100% on the .item element, but that doesn’t seem to work.

Can anyone explain why this is happening and how I can get my flex item to take up the full height of its parent container?

2

Answers


  1. You were close but missed the height attribute on the child div. Set .item to height: 100%.

    .container {
      display: flex;
      flex-direction: column;
      height: 300px;
      background-color: #f0f0f0;
      padding: 20px;
    }
    
    .item {
      height: 100%;
      background-color: #fff;
      padding: 20px;
      border: 1px solid #ddd;
    }
    <div class="container">
      <div class="item">This is my flex item</div>
    </div>
    Login or Signup to reply.
  2. height: 100% – is bad, because it push out other elements, if they appear. Use flex-grow: 1:

    .container {
      display: flex;
      flex-direction: column;
      height: 300px;
      background-color: #f0f0f0;
      padding: 20px;
    }
    
    .item {
      background-color: #fff;
      padding: 20px;
      border: 1px solid #ddd;
      flex-grow: 1;
    }
    <div class="container">
      <div class="item">This is my flex item</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search