Search code examples
javascriptjquerycssvertical-alignment

Vertical adaptive image alignment on adaptive layout


This is my code :

HTML

<html>
<body>
  <div id="id">
    <div class="one">
      <img>
    </div>
    <div class="two">
      <img>
    </div>
    <div class="one">
      <img>
    </div>
  </div>
</body>
</html>

CSS

div{
float : left;
width : 33,3%
height : 100%;
}

img{
max-width : 100%;
max-height : 100%;
}

div#id{
position : fixed;
top : 0;
bottom : 0;
left : 0;
right : 0;
}

I have been looking for this for ages and can't figure it out...

Unknown height of divs and images images can change. How can I vertical align the images inside the divs class="one"? as this is an adaptive layout, images must be scaled to prevent overflow.

table-cell or line-height = 100% doen't seem to work.

Do I realy need javascript here? I have tried a jquery code but it is above my knowledge and ends up changing the margin of all the images in my website... here it is :

$(document).ready(function() {                  
  $(".one").each(function(){
    var wrapH = $(".one").outerHeight();
    var imgH = $("img").outerHeight();
    var padTop = (wrapH-(imgH))/2;
      if (padTop>0){
        $("img").css("margin-top", padTop + "px");
      }
  });
});

Solution

  • Ok I finaly found a solution using jquery thx to bdmoura in this post : https://stackoverflow.com/users/2442497/bdmoura He showed me how to set an adaptive margin to the images according to image and div height. here is th jquery code :

    $(document).ready(function() {
      $(".one").each(function(){
        var wrap = $(this),
        wrapH = wrap.outerHeight(),
        img = wrap.find('img'),
        image = new Image(),
        imgH = 0,
        padTop = 0;
    
        image.onload = function () {
            imgH = img.outerHeight();
            padTop = ( wrapH - ( imgH ) )/2;
            if ( padTop > 0 ){
                 img.css("margin-top", padTop + "px");
            }
        }
    
        image.src = img.attr('src');
    
      });
    });
    

    thx to him!