Search code examples
cssbootstrap-4responsive

CSS bootstrap keep at least 2 columns


I have the following HTML:

  <div class="row">
    <div class="col-md-3 col-sm-6">
      <img src="image1.jpg" width="80%">
      <h4>Text under image 1</h4>
    </div>
    <div class="col-md-3 col-sm-6">
      <img src="image2.jpg" width="80%">
      <h4>Text under image 2</h4>
    </div>
    <div class="col-md-3 col-sm-6">
      <img src="image3.jpg" width="80%">
      <h4>Text under image 3</h4>
    </div>
    <div class="col-md-3 col-sm-6">
      <img src="image4.jpg" width="80%">
      <h4>Text under image 4</h4>
    </div>
  </div>

The images are all 485x900 pixels. On wide screens, there are 4 columns. If the viewport is smaller, e.g. 1000 pixels, there are 2 columns and if it is very small, e.g. 600 pixels, there is only 1 column.

However, I want to keep at least 2 columns, no matter how small the viewport is. The CSS shall shrink the images to fit.

How can I achieve this?


Solution

  • Bootstrap is "mobile-first" so always start with the smallest viewport and work up. The classes with no breakpoint in them apply to the smallest viewport and up. The classes with breakpoints apply to that size and up, overriding the smaller breakpoint classes.

    Use .col-6.col-md-3, this will start out half the width of the screen and then break to 25% at the medium breakpoint.

      <div class="row">
        <div class="col-6 col-md-3">
          <img src="image1.jpg" width="80%">
          <h4>Text under image 1</h4>
        </div>
        <div class="col-6 col-md-3">
          <img src="image2.jpg" width="80%">
          <h4>Text under image 2</h4>
        </div>
    
        <!-- ... -->
    
      </div>
    

    https://getbootstrap.com/docs/4.6/layout/grid/#mix-and-match