使用CSS而不是jquery将图像置于div中

我正在尝试将任何大小的图像放在(总是)方形div中,并在父div的大小改变时保留方面。 这就是我正在做的事情:

CSS:

.photo_container { width: 250px; height: 250px; overflow: hidden; border-style: solid; border-color: green; float:left; margin-right:10px; position: relative; } .photo_container a img{ position:absolute; } 

HTML

     

使用Javascript:

 // fix image size on load $(".photo").one("load", function() { fixImage($(this)); }).each(function() { if(this.complete) $(this).load(); }); // Just to test if everything's working fine $(".photo").on("click",function(){ var rand = Math.floor(Math.random() * 200) + 80; $(this).parent().parent().width(rand); $(this).parent().parent().height(rand); fixImage($(this)); }); // Brings the photo dead center function fixImage(obj){ //alert("something changed"); var pw = obj.parent().parent().width(); var ph = obj.parent().parent().height(); var w = obj.width(); var h = obj.height(); console.log(w+" "+pw); if(h>w){ var top = (h-ph)/2; obj.css("top",top*-1); }else{ var left = (w-pw)/2; obj.css("left",left*-1); } } 

工作示例: http//jsfiddle.net/vL95x81o/4

如何在不使用jquery但仅使用CSS的情况下完成此操作? 如果div的大小永远不会改变,那么这个解决方案就没问题了。 但我正在研究响应式设计,看起来像photo_container div的大小可能需要根据屏幕的大小进行更改(通过CSS)。

以下是裁剪前的照片:

肖像图像 景观图像

其他人发布的后台解决方案是我最初的想法,但如果您仍想使用图像,那么您可以执行以下操作:

CSS:

 .photo_container { width: 250px; height: 250px; overflow: hidden; border-style: solid; border-color: green; float:left; margin-right:10px; position: relative; } .photo_container img { min-width: 100%; min-height: 100%; position: relative; top: 50%; left: 50%; transform: translateY(-50%) translateX(-50%); } 

HTML:

   

这将使内部的任何图像为100%高或100%宽,具体取决于最短属性,并将它们水平和垂直集中。

编辑

值得注意的是IE8或Opera Mini不支持转换 – http://caniuse.com/#feat=transforms2d

你可以这样做:

http://jsfiddle.net/vL95x81o/5/

 

使用背景图片。

 .photo_container { width: 250px; height: 250px; overflow: hidden; border-style: solid; border-color: green; float:left; margin-right:10px; position: relative; } .photo_container a{ /* Set the background size to cover to scale the image */ background-size: cover; /* Position the image in the center */ background-position: 50% 50%; background-repeat: no-repeat; position:absolute; width: 100%; height: 100%; } 
 

我没有使用背景图像或JS解决了这个问题。 高度来自容器中的before标签。 100%的填充等于100%的填充。 所以高度总是相同的宽度。

http://jsfiddle.net/a1rLeq06/