Hai Tien
Hai Tien

Reputation: 3117

How to fluid images when resize window?

How to fluid images when resize window?.

I have HTML code like this :

<div class="box">
 <img src="http://demo.smooththemes.com/magazon/wp-content/uploads/2013/01/984632486_9d8ff89b63_b-642x336.jpg" />
</div>

And CSS :

.box {width:150px; height:60px; position:relative; overflow:hidden}
.box img{position:absolute; width:180px; height:80px; top:-10px; left:-10px}

When windows is resized, I want remove properties of (.box img): top:-10px; left:-10px and attribute more : min-width:100%, max-width:100%. It means we have :

.box img{
position:absolute;
width:180px; height:80px; min-width:100%;  
top:(removed); left:(removed)}

How can I do it with Javascript or Jquery. Thanks for your help.

Upvotes: 1

Views: 167

Answers (4)

damian
damian

Reputation: 5444

I think this script by Scott Jehl could be interesting for you although the images only change there dimensions at specific breakpoints.

picturefill

It's very useful as you can define different picture sources for various resolutions.

The markup needed in combination with this script looks e.g. like this:

<span data-picture data-alt="Image description">
    <span data-src="small.jpg"></span>
    <span data-src="medium.jpg"     data-media="(min-width: 400px)"></span>
    <span data-src="large.jpg"      data-media="(min-width: 800px)"></span>
    <span data-src="extralarge.jpg" data-media="(min-width: 1000px)"></span>

    <!-- Fallback content for non-JS browsers. Same img src as the initial, unqualified source element. -->
    <noscript>
        <img src="external/imgs/small.jpg" alt="Image description">
    </noscript>
</span>

Upvotes: 1

Stuart Kershaw
Stuart Kershaw

Reputation: 17671

I tend to agree with @Phorden that media queries are a good route for this.

However, if you need to do it with JS / jQuery:

$(window).resize(function() {
    $('.box img').css({'top': 'auto', 'left': 'auto', 'min-width': '100%'});
});

Upvotes: 3

Jonathan Marzullo
Jonathan Marzullo

Reputation: 7031

add max-width:100% and height:auto to your images to make them resize proportional based on their parent:

.box img{
       position:absolute; 
       top:-10px; 
       left:-10px

       max-width: 100%; /* fits width of parent */
       height: auto;  /* resize height based on max-width, making it proportional *?
 }

.

Upvotes: 1

Phorden
Phorden

Reputation: 1034

I don't know about a jQuery or Javascript solution, but if you want a pure CSS solution, CSS media Queries is probably what you want. It is a foundational concept of responsive web design. More info on CSS Media Queries here: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries

Upvotes: 3

Related Questions