Search code examples
csslayoutsticky-footer

CSS Position element on bottom of container without removing it from flow


I have a container with 3 children elements.

<div class="container">
  <img />
  <div class="element1"></div>
  <div class="element2 bottom"></div>
</div>

They must be positioned as shown on the diagram below:

  • image is in the top of the left column and nothing goes below it (it is the only element in the left column)
  • element1 is in the top of the right column
  • element2 is stick to the bottom of the right column (and must not collide with the element1 which is above it)

enter image description here

Does somebody know how to achieve such layout using pure CSS? Ideally I wouldn't like to add any markup, but I can do that if that's the only possible way.

The biggest problem I'm facing here is how to stick that second element (non-image) to the bottom of the container without removing it from the flow. Because if I use position: absolute and remove it from the flow, the elment above it can collide with it (both elements have unknown height).

Here's a pen to work on: http://codepen.io/anon/pen/yNwGvQ


Solution

  • I would suggest you to use two columns in your html and then use the property display: flex; for your right column as suggested in the article A Complete Guide to Flexbox.

    http://codepen.io/AlexisBertin/pen/QboYyY

    All the HTML:

    <div class="container">
      <div class="column column-left">
        <div class="image">This is an image</div>
      </div>
      <div class="column column-right">
        <div class="element1">This container has dynamic content so it's height is unknown and may change.<br/><br/> Some random content to make it larger. Some random content to make it larger. Some random content to make it larger. Some random content to make it larger. Some random content to make it larger.</div>
        <div class="element2">This container also has dynamic content so it's height is unknown and may change</div>
      </div>
    </div>
    

    Part of this CSS:

    .column {
      float: left;
      height: 100%;
    }
    .column.column-left { width: 100px; }
    .column.column-right { 
      width: calc(100% - 100px);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    

    Hope you get the idea. Good Luck'.

    EDIT:

    The easiest way to achieve this without declaring height to the container seems to only create a third parent div to the first block of the second column and define it as flex: 1; while the second block of this same second column would be define as flex: 0;.

    http://codepen.io/anon/pen/yNwZmJ

    More details explained in the comments.