palaѕн
palaѕн

Reputation: 73896

How to resize image on mobile devices using jQuery?

I am working on a mobile website and I have a div & image inside it like this:

<div id="wrapper">
    <div id="content">My img tag here</div>
</div>

I want to know, how I can resize the image on any phone/tablet without worrying about its resolution, size or orientation. Here, I am looking for the best possible solution based on the above scenarios.

Upvotes: 3

Views: 1830

Answers (3)

palaѕн
palaѕн

Reputation: 73896

I found a simple solution using jquery....

$(document).ready(function() {

    $width = $('#content').width();

    $('#content img').css({
        'max-width': $width,
        'height': 'auto'
    });
});

Upvotes: 0

Endre Simo
Endre Simo

Reputation: 11551

The above mentioned technique is the most widespread, but as i understand the solution desired shouldn't be dependent about device size, screen resolution or orientation.

I only mention two clever solution, none of them handle this job on CSS:

https://github.com/adamdbradley/foresight.js

http://adaptive-images.com/

The second solution is clever one, because it captures the screen resolution of visitor's device, automatically creates caches and deliver the most appropriated image size of embedded html <img> markup.

Note: One mention though: this is server dependent solution, and should be used only in PHP code environment.

...and here is a jquery plugin which for the same purposes: https://github.com/teleject/hisrc

Upvotes: 1

Brett Gregson
Brett Gregson

Reputation: 5913

You can use media queries to give CSS attributes depending on the orientation:

@media screen and (orientation:portrait) {
    img {
        // css attributes
    }
}

@media screen and (orientation:landscape) {
    img {
        // css attributes
    }
}

Or you could do it for screen width:

@media screen and (max-width: 500px) {
    img {
        // css attributes
    }
}

Upvotes: 2

Related Questions