Home > Mobile >  Shrink flex elements if window is too narrow
Shrink flex elements if window is too narrow

Time:12-01

I am using a flexbox on my site to display post previews as tiles. Each one is a fixed size (384*384px) and displays as a grid that fits as many tiles in each row as it can horizontally and it rearranges itself dynamically as the page is resized. This is the current CSS for this:

.post-list { display: flex; flex-wrap: wrap; }
.post-tile { flex: 0 0 384px; width: 384px; height: 384px; margin: 10px; padding: 30px; box-sizing: border-box; overflow: hidden; border-radius: 32px; }

I would like it to do one extra thing though if possible: If the window is narrower than the width of one of the tiles I would like it to resize the tiles down to fit in the screen while also keeping the height and width the same, but I don't know how to accomplish this.

Here is a JS Fiddle with this CSS filled out with a few basic tiles.

CodePudding user response:

You are probably looking for flex-shrink: 1; which allows your item to shrink.

Note: You probably also want to play around with your padding for the .post-list element

See Example below

.post-list {
     display: flex;
     flex-wrap: wrap;
     
     /*below two properties are for demonstration only*/
     max-width: 200px;
     border: 1px solid black;
}
 .post-tile {
     flex: 0 0 384px;
     width: 384px;
     height: 384px;
     margin: 10px;
     padding: 30px;
     box-sizing: border-box;
     overflow: hidden;
     border-radius: 32px;
     background-color:lightgrey;
     flex-shrink: 1; /* this allows to shrink your item */
}
<ul >
  <li >
    <h3>
      Title 1
    </h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </li>
  <li >
    <h3>
      Title 2
    </h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </li>
  <li >
    <h3>
      Title 3
    </h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </li>
  <li >
    <h3>
      Title 4
    </h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </li>
  <li >
    <h3>
      Title 5
    </h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </li>
</ul>

CodePudding user response:

Currently you have it like this

flex: 0 0 384px

Change it to

flex: 0 1 384px

That second value is flex-shrink. It will solve the problem.

  • Related