Home  >  Q&A  >  body text

Getting table columns to stack on mobile view is my goal

I have 5 columns and I'm making them a table because that's the easiest way for me to code.

I want them to stack on the mobile view. How do I do this?

My format is:

#container {
  display: table;
  width: 100%;
  table-layout: fixed;
  padding: 10px;
}

.content {
  display: table-cell;
  text-align: center;
  border: 5px solid black;
  word-wrap: break-word;
}

.content img {
  width: 100%;
  height: 100%;
  display: table-header-group;
}
<div id="container">
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
  <div class="content"></div>
</div>

Any help would be greatly appreciated. I tried using a media query to set the content class to 100% width. I'd like them to be stackable if possible. I'm not sure where I went wrong.

I tried using flexbox before the table method but ran into issues with the height when the screen size changes, this is easier for me to do, I just don't know how to make it mobile responsive. Since it's not an actual table, I'm a little confused.

P粉821231319P粉821231319180 days ago277

reply all(1)I'll reply

  • P粉803527801

    P粉8035278012024-04-03 14:20:30

    If you like your current desktop setup, the easiest way is to wrap all the CSS above in a @media query to accommodate larger screens. Like @media (min-width: 768px) { ... all your CSS } - This way, nothing on mobile devices will be affected by these styles. By default, div is a block-level element and will be 100% stacked.

    /* COMMON STYLES THAT WILL AFFECT ALL SCREENS - just for presentation and can be removed */
    
    .content {
      border: 5px solid black;
      background: blue;
      height: 20px;
      margin-bottom: 10px;
    }
    
    
    /* now this will only apply to larger screens */
    
    @media (min-width: 768px) {
      #container {
        display: table;
        width: 100%;
        table-layout: fixed;
        padding: 10px;
      }
      .content {
        display: table-cell;
        text-align: center;
        word-wrap: break-word;
        /* REMOVE THIS from your real code, just a reset from the global above */
        margin-bottom: 0;
        background: transparent;
        height: auto;
      }
      .content img {
        width: 100%;
        height: 100%;
        display: table-header-group;
      }
    }
    <div id="container">
      <div class="content"></div>
      <div class="content"></div>
      <div class="content"></div>
      <div class="content"></div>
      <div class="content"></div>
    </div>

    reply
    0
  • Cancelreply