缩放图像保持纵横比,然后在流体高度和宽度DIV内垂直和水平居中

pho*_*ode 5 css image centering fluid-layout

好的,这有点拗口,非常具体.我会尽力解释!

目标是在缩放图像时保持纵横比,并使其在DIV内垂直和水平居中,而DIV仅由百分比定​​义.图像需要保持最佳匹配,因此如果需要最大宽度,则使用它,反之亦然.

使用Firefox 33版(或一些早期版本)来查看这个js小提琴,看它是否正常工作:

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>
Run Code Online (Sandbox Code Playgroud)

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 the characters like 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%;
}
Run Code Online (Sandbox Code Playgroud)

问题:

我最初在stackoverflow上找到了我的代码,并创建了一个简单的mod,为.centered类添加了max-height/width.当时,这适用于所有主流浏览器.唯一的例外是Opera.

垂直对齐div内的图像和响应高度

但是有一个很大的问题:最新版本的Chrome(版本38.0.2125.111)不再适用于此代码,我的用户更喜欢使用Chrome浏览器.

关于如何解决这个问题的任何想法?这是Chrome的错误吗?我愿意接受javascript建议,以便再次使用.

Pau*_*ull 6

我想出了这个:以JSFiddle为中心的图像将长宽比保持在可调整大小的流体容器中

.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

图像水平和垂直居中.如果缩小窗口,则图像会缩小原始宽高比.

我没有在所有浏览器上测试它.


小智 1

看看CSS object-fit属性:

不过,对于旧版浏览器,您可能需要一个polyfill

查看浏览器对对象适配的支持。