Search code examples
htmlcsscss-tables

Stacking a table with an image on mobile using html/css


Very new to all this and playing around with having a two column button (of sorts) that will feature a coloured background with some text on one side and an image (which will also be a link) on the other.

I also want this to stack on mobile. I have had some success using other snippets of code found on here, but I can't get it quite right - mainly the left side of my 'button' doesn't fill the whole side.

There's probably a really simple solution, but I can't seem to find it right now!

* {
  box-sizing: border-box;
}

.column {
  float: left;
  width: 50%;
  align-content: center;
}

.row {
  max-width: 280px;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .column {
    width: 100%;
  }
}
<div class="row">
  <div class="column" style="background-color:#aaa;">
    <p>Some text..</p>
  </div>
  <div class="column">
    <img src="https://gallery.mailchimp.com/e31ffc7f9716689ceb3f1e8be/images/65235be8-d229-4c50-801e-36f5bccbf429.jpg">
  </div>
</div>


Solution

  • I would use flex rather than floats (the advantage is you get equal height columns):

    * {
      box-sizing: border-box;
    }
    
    .column {
      width: 50%;
    }
    
    .column>img {
      width: 100%;    /* just makes the image resize to the column */
      display: block; /* removes space below image */
    }
    
    .row {
      max-width: 280px;
      display: flex;   /* use flex instead of floats */
    }
    
    @media screen and (max-width: 600px) {
      .row {
        flex-direction: column;  /* change direction of flex to columns at small screen size */
      }
      .column {
        width: 100%;              /* make column full width */
      }
    }
    <div class="row">
      <div class="column" style="background-color:#aaa;">
        <p>Some text..</p>
      </div>
      <div class="column">
        <img src="https://gallery.mailchimp.com/e31ffc7f9716689ceb3f1e8be/images/65235be8-d229-4c50-801e-36f5bccbf429.jpg">
      </div>
    </div>