Search code examples
htmlcsssassalignmentflexbox

How to float an image and center headlines in remain space?


I want this structure, a container that has flex:display, an image floating on the right, then a h1 and h2, I want to put these vertical and horizontal center on the remaining space of the div.

This is my current result.

enter image description here

Mockup.

+-----------------------+
|                       |
|XXXX                   |
|XXXX     HELLFISH      |
|XXXX    born to die    |
|XXXX                   |
|                       |
+-----------------------+

This is the html code.

div.container
  img(src='http://vignette3.wikia.nocookie.net/simpsons/images/a/a1/Flying_Hellfish_Logo.png/revision/latest?cb=20150327234211')
  h1 HELLFISH
  h2 Born to die

The SCSS.

.container{
  display: flex;
  width: 50%;
  border: 1px solid red;
  justify-content: space-between;
  img{
    max-width: 300px;
    max-height: 300px;
    float: left;
  }
  h1{
    align-self: center;
    margin: auto;
    position: relative;
  }
  h2{
    align-self: center;
    margin: auto;
    vertical-align:middle;
    position: relative;
  }  
 }

The codepen. http://codepen.io/TabaresSotelo/pen/pRyxPz

Best regards


Solution

    • Wrap the h1 and h2 in one container (which becomes a sibling flex item of the image).
    • Use the order property to shift the image to the right.
    • You don't need to use the float property or justify-content: space-between.

    .container {
      display: flex;
      width: 50%;
      border: 1px solid red;
    }
    .nested-container {
      flex: 1; /* to consume all remaining space */
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .container img {
      max-width: 300px;
      max-height: 300px;
      order: 1;
    }
    h1, h2 {
      margin: 0;
    }
    <div class="container">
      <img src="http://vignette3.wikia.nocookie.net/simpsons/images/a/a1/Flying_Hellfish_Logo.png/revision/latest?cb=20150327234211" />
      <div class="nested-container">
        <h1>HELLFISH</h1>
        <h2>Born to die</h2>
      </div>
    </div>

    revised codepen (compiled code)