Search code examples
htmlcsspositioncss-positionmultiple-columns

Three Divs on Top of Each-Other Within Left Column - No Bootstrap - HTML / CSS


I'm having trouble trying to stack three divs on top of each-other within a left-column div. Here's what I'm trying to achieve:

enter image description here

I'm attempting to use the solution found in this question, so I have this:

.main-div {
  border: 1px solid black;
}

.main-div-line-1 {
    border-bottom: 1px solid rgba(0,0,0,.125);
    padding: 5px;
    font-family: "Proxima Nova Bold";
    font-size: 20px;
    text-align: center;
}

.main-div-line-2 {
    display: flex;
}

/*parent*/
.inner-main-left {
    display: flex;
    position: relative;
}
/*child*/
.inner-left-left-top {
    position: absolute;
}
/*child*/
.inner-left-left-middle {
    position: absolute;
}
/*child*/
.inner-left-left-bottom {
    position: absolute;
}

.inner-main-right {
    display: flex;
}

#main-kitty-image {
    width: 360px;
}
<div class="main-div">
  <div class="main-div-line-1">
    Kitty Averages
  </div>
  <div class="main-div-line-2">
    <div class="inner-main-left">
      <div class="inner-left-left-top">
        helloKitty Top
      </div>
      <div class="inner-left-left-middle">
        helloKitty Middle
      </div>
      <div class="inner-left-left-bottom">
        helloKitty Bottom
      </div>
    </div>
    <div class="inner-main-right">
      <img id="main-kitty-image" src="https://i.imgur.com/JmY6X13.jpg"/>
    </div>
  </div>
</div>

Isn't the idea to have the parent div, in this case, inner-main-left as position: relative and then the inner divs, inner-left-left-top, inner-left-left-middle and inner-left-left-bottom, each as position: absolute?

.inner-main-left and .inner-main-right are both children of .main-div-line-2. We want those two side by side, which is why I'm displaying them both as flex. But that shouldn't alter their ability to stack divs on top-of each-other within them, right?

If you run the snippet above or visit this JSFiddle, you'll see that this is not working.


Solution

  • As is pointed out in the article that @Paulie_D linked, the key is to add flex-direction: column to the div that you want to act as a parent column.

    Then for the children within that div, you can set flex-grow, flex-shrink and flex-basis like this:

        .inner-left-left-top {
           flex: 0 0 100px;
        }
    
        .inner-left-left-middle {
            flex: 0 0 100px;
        }
    
        .inner-left-left-bottom {
            flex: 0 0 100px;
        }
    

    Working JSFiddle and see MDN Flex