Image de hauteur variable de centrage vertical tout en maintenant la largeur / hauteur maximale

Je souhaite centrer une image de largeur / hauteur inconnue sur une page, tout en vous assurant qu'elle se rétrécit si elle est plus grande que la page (c. max-width d. Utiliser la max-width max-height / max-height ).

J'ai essayé d'utiliser l' display:table-cell méthode de display:table-cell , mais la max-width est ignorée dans Firefox pour tous les éléments contenus dans les éléments déclarés avec display:table-cell . Existe-t-il un moyen de centrer verticalement un élément de hauteur variable sans utiliser l' display:table-cell ?

Je peux changer la note. JavaScript est acceptable, mais je ne peux pas utiliser JQuery (ou toute autre bibliothèque JS).

Cela devrait s'avérer très bien … pas de JavaScript nécessaire 🙂

Voir la démonstration de travail sur jsFiddle .

CSS

 /* Don't Change - Positioning */ .absoluteCenter { margin:auto; position:absolute; top:0; bottom:0; left:0; right:0; } /* Sizing */ img.absoluteCenter { max-height:100%; max-width:100%; } 

HTML

 <img class="absoluteCenter" src="PATHTOIMAGE"> 

Remarque: Cette classe peut être utilisée pour tout simplement. Si vous utilisez ceci pour autre chose qu'une image, assurez-vous d'ajouter une règle TAG.absoluteCenter avec une max-height max-width de votre choix (où TAG est la balise HTML que vous utilisez [par ex. div.absoluteCenter ] Et max-width / max-height est inférieur à 100% ).

Essayez quelque chose comme ça …

Demo: http://jsfiddle.net/wdm954/jYnk8/1/

 $(function() { h = $('.img').height(); w = $(window).height(); if (h < w) { $('.img').css('margin-top', (w - h) /2 + "px"); } else { $('.img').height(w); } }); 

(Vous pouvez tester différentes tailles en modifiant certains CSS que j'ai signalés.)

Voici une façon avec javascript:

 <html> <head> <style> html, body{ height:100%; margin:0; border:0; padding:0; background:#000; } body{ position:relative; } img{ border:0; padding:0; margin:0 auto; max-width:100%; max-height:100%; display:block; position:absolute; } </style> </head> <body> <img /> <script> (function(){ var imgs = [ 'http://farm3.static.flickr.com/2396/2078094921_ee60c42d0f.jpg', 'http://farm6.static.flickr.com/5242/5353846171_9169f810dc_b.jpg', 'http://farm6.static.flickr.com/5284/5336493514_8e41696b66_b.jpg' ], img = document.getElementsByTagName('IMG')[0], getStyle = function(elm){ return window.getComputedStyle ? window.getComputedStyle(elm) : elm.currentStyle; }, bodyStyle = getStyle(document.body), toInt = function(pxSize){ return +pxSize.replace(/px/,''); }, chgImg = function(){ img.src = imgs[i++ % imgs.length]; img.onload = function(){ var imgStyle = getStyle(img); img.style.left = ( toInt(bodyStyle.width) - toInt(imgStyle.width) ) / 2 + 'px'; img.style.top = ( toInt(bodyStyle.height) - toInt(imgStyle.height) ) / 2 + 'px'; img.onload = null; }; }, i = 0; chgImg(); setInterval(chgImg, 3000); })(); </script> </body> </html>​