Search code examples
csscss-positionabsolute

Why doesn't (the standard way of) making an element 100% the height of its parent work in Safari when the parent's a flex item?


I'm using the method of making a child element 100% the height of its parent that's most commonly given in StackOverflow answers, namely relative-positioning the parent, and then giving the child these styles:

position: absolute;
top: 0px;
bottom: 0px;
width: 100%;
height: 100%;

But, please take a look at this Codepen implementation of the above. In it, I make the parent element a flex item and the child element a table (or a <div> with display: table). I need to do this for my client's real world design case, partly to vertically align the text in the middle, which I believe only tables can do.

As you can see, it breaks in Safari. But It looks like the CSS should work, and it does in Chrome. Why's it breaking in Safari? How can I fix this?

PS: I'm open to alternative approaches to making the child 100% the height of its flex item parent, if necessary.


Solution

  • If you make the parent display: flex; flex-direction: column; and the child flex-grow:1; it should work.

    <div class="parent">
      <div class="child">
          Content
      </div>
    </div>
    
    .parent{
      display:flex;
      flex-direction: column;
      background:blue;
      height: 300px;
    }
    
    .child{
      flex-grow:1;
      background:red;
      display:flex;
      align-items:center;
    }
    

    Check this code pen