Thursday 15 April 2010

css - Scale image maintaining aspect ratio, then center vertically and horizontally inside fluid height and width DIV -



css - Scale image maintaining aspect ratio, then center vertically and horizontally inside fluid height and width DIV -

ok, bit of mouthful , super specific. seek best explain!

the goal maintain aspect ratio while scaling image , keeping vertically , horizontally centred within div defined percentages. image needs maintain best fit, if max width required it's used , vice versa.

use firefox version 33 (or few before versions) view js fiddle see working properly:

http://jsfiddle.net/3vr9v2fl/1/

html:

<div id="imageviewer" > <div class="dummy"></div> <div class="img-container centerer" id="imagevieweroriginal"> <img class="centered" src="http://chrisnuzzaco.com/couch/uploads/image/gallery/smiling_woman_wearing_drivers_cap.jpg" alt="doctor concentrating on work"></img> </div> </div> </div>

css:

#imagewrapper{ position:absolute; width:69%; height:100%; top:0px; bottom:0px; background-color:gray; } #imageviewer{ position:relative; width:100%; height:100%; } .responsive-container { position: relative; width: 100%; border: 1px solid black; } .dummy { padding-top: 100%; /* forces 1:1 aspect ratio */ } .img-container { position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .centerer { text-align:center; /* align center inline elements */ font: 0/0 a; /* hide characters spaces */ } .centerer:before { content: ' '; display: inline-block; vertical-align: middle; height: 100%; } .centered { vertical-align: middle; display: inline-block; max-height: 100%; max-width: 100%; }

the problem:

i found code here on stackoverflow , made simple mod adding max-height/width .centered class. @ time, worked in major browsers. exception beingness opera.

vertically align image within div responsive height

there big problem however: latest version of chrome (version 38.0.2125.111) no longer works code , users prefer chrome other browsers big margin.

any ideas on how solve this? bug chrome? i'm open javascript suggestions create work again.

i came this: jsfiddle - centered image keeps aspect ratio in resizable fluid container

class="snippet-code-css lang-css prettyprint-override">.container { position: absolute; top: 0; left: 0; bottom: 0; right: 0; width: 100%; height: 100%; } .image { position: absolute; max-width: 100%; max-height: 100%; top: 50%; left: 50%; transform: translate(-50%, -50%); } body { width: 100%; height: 100%; position: absolute; margin: 0; } class="snippet-code-html lang-html prettyprint-override"><div class='container'> <img class='image' src='http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/sample1_l.jpg'> </div>

the image stays centered both horizontally , vertically. if window scaled downwards image shrinks respecting original aspect ratio.

i didn't test on browsers though.

css image centering fluid-layout

No comments:

Post a Comment