Search code examples
cssimageonclickscale

How to scale images to the size of an existing div while you change them dynamically with onClick?


What I am trying to do is the following.

  1. I have a list of hidden images.
  2. I have a button activated with Jquery onclick that replaces the html of a div to include the images
  3. The button functions as a cycle button and gets a big list of images.

My problem is that the images do not scale to the size of the parent div. Even if I give them a .horizontal and .vertical class Any ideas?

I want to keep the format of the hidden list of images inside a div because i do some other things with the lists. I originally thought that by having two classes for the images it will work and now that I am finishing I realised that the whole idea has a problem !

http://jsfiddle.net/alexnode/ttQHt/

HTML
    <div id="artdiv2">
        <div id="artslide1nextbutton">></div>
        <div id="artslide1"></div>
    </div>
    <div class="hidden">
    <div id="1slide1">
        <img class="horizontal" src="http://farm8.staticflickr.com/7366/9160515864_7dc851a598.jpg"  alt="Rezando a los antiguos Dioses - Praying to the old Gods">
    </div>
    <div id="1slide2">
        <img class="vertical" src="http://farm6.staticflickr.com/5519/9158661396_4828a06655.jpg"  alt="Drain">
    </div>
        </div>

Jquery
//i get everything called 1slide like that. 
var artslides = $('[id^=1slide]');
idxs1 = 1;
//this is my button that cycles through the image 
$("#artslide1nextbutton").on(
    "click", function () {
    $("#artslide1").html(artslides.eq(idxs1).html());
    idxs1 = idxs1 == 1? 0 : idxs1 + 1;
});

CSS
.hidden{display:none;}
#artdiv2{ position:absolute;  top:8%; left: 20%; height:70%; width:100%; background:DimGray;}
#artslide1nextbutton{position:fixed;  top:0px; left: 0px; height:auto; width:10%; background:DarkRed;pointer:cursor;}
.horizontal {position:relative; width:100%; height:auto;}
.vertical {position:relative; height:100%; width:auto;} 

Solution

  • EDIT : answer updated to fit closer to question.:

    you could play width min and max value and center img with text-align:center.

    demo http://jsfiddle.net/ttQHt/2/

        #artslide1 {
            width:100%;
            overflow:hidden;
            height:100%;
            text-align:center;
        }
    #artslide1 img {
        min-height:100%;
        max-width:100%;
    
    }
    

    Some other option to play with image

    here is an idea of what happens if you can set line-height. http://codepen.io/gcyrillus/pen/BdtEj and adding min-width/min-height http://codepen.io/anon/pen/kfIbp