htmljquery-mobilemobilecss

Have image fit 100% width on mobile platforms


so I am currently implementing a mobile version to my website and everything is fine except I want to be able make it so the image will fill 100% width of the screen whether the user tuns it horizontally or vertically. The image fits 100% like normal on any non-based mobile platform, but does not on a mobile device. Any suggestions?

I currently am using

.blog{
    padding:10px;
    border-bottom:2px solid #eeeeee;
    padding:10px;
    background:#ececec;
}
.blog-img{
    text-align:left;
    width:100%;
    margin:0 auto;
    padding:10px 0 5px 0;
}

I've also tried:

min-width:100%;

Solution

  • The image fits 100% like normal on any non-based mobile platform, but does not on a mobile device.

    It is not working as expected because you are giving the parent element .blog-img a width of 100%.

    You need to directly target the nested img descendant element and give it a width of 100%:

    .blog-img img {
      height: auto;
      width: 100%;
    }
    

    Depending on what you're trying to achieve, setting a min-width of 100% may be better in certain cases.

    .blog-img img {
      height: auto;
      min-width: 100%;
    }
    

    Here is an minimal example highlighting the difference:

    <p>Using <code>max-width: 100%</code></p>
    <img style="max-width: 100%;" src="http://placehold.it/50" />
    
    
    <p>Using <code>width: 100%</code></p>
    <img style="width: 100%;" src="http://placehold.it/50" />

    Since you're optimizing your site for mobile browsers, be sure to set a viewport meta tag:

    <meta name="viewport" content="width=device-width, initial-scale=1">