csstwitter-bootstrap-3media-queriesscreen-size

CSS command not running in media query


I know this may have already duplicated, but I tried many of the solutions on the internet and still doesn't work. I have two pictures that wishes to appear in different screen sizes. However, the CSS command picture for smaller screen (767px and below) does not seem to work.

I would be so grateful if you could help out a newbie here. Thank you.

        @media only screen and (min-width: 768px) {
            img{
                border-top-left-radius: 30px;
                border-bottom-left-radius: 30px;
            }
        }

        @media only screen and (max-width: 767px) {
            #loginPicXs{
                border-top-left-radius: 30px;
                border-top-right-radius: 30px;
            }
        }
                <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
                    <picture>
                        <source media="(max-width: 767px)" id="loginPicXs" srcset="loginformpic_sm_xs.jpg">
                        <img src="loginformpic.jpg" class="img-responsive">
                    </picture>
                </div>


Solution

  • You need to use the attribute srcset when using the <source>-element. It's usage is for using different images for different viewports, where the images can keep their intrinsic height & width-values to e.g. avoid cumulative layout shifts.

    Although the <source>-element shouldn't really be used with only one image in the srcset-attribute, you can keep your HTML markup by just using srcset instead of src.

    As for the CSS, just apply your desired properties on the img - not on the <source>-element.

    @media only screen and (min-width: 768px) {
      img {
        border-top-left-radius: 30px;
        border-bottom-left-radius: 30px;
      }
    }
    
    @media only screen and (max-width: 767px) {
      img {
        border-top-left-radius: 30px;
        border-top-right-radius: 30px;
      }
    }
    <picture>
      <source 
        srcset="https://picsum.photos/200"
        media="(max-width: 767px)"
      />
      <img 
        src="https://cdn.pixabay.com/photo/2015/03/17/02/01/cubes-677092__480.png"
      />
    </picture>