如何模仿背景大小:覆盖<img>?

如何调整图像大小并将其重新定位在一个盒子中,以覆盖整个盒子的方式,类似于background-size: cover工作方式。

 <div class="box" style="width: 100px; height: 100px;"> <img src="pic.jpg" width="413" height="325"> </div> 

我知道我必须添加overflow:hidden到框和图像需要的position: absolute 。 但是这个公式是什么让我的形象正确的新大小,并离开+顶部位置?

这可能会更容易

jQuery的

 $('.box').each(function() { //set size var th = $(this).height(),//box height tw = $(this).width(),//box width im = $(this).children('img'),//image ih = im.height(),//inital image height iw = im.width();//initial image width if (ih>iw) {//if portrait im.addClass('ww').removeClass('wh');//set width 100% } else {//if landscape im.addClass('wh').removeClass('ww');//set height 100% } //set offset var nh = im.height(),//new image height nw = im.width(),//new image width hd = (nh-th)/2,//half dif img/box height wd = (nw-tw)/2;//half dif img/box width if (nh<nw) {//if portrait im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left } else {//if landscape im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top } }); 

CSS

 .box{height:100px;width:100px;overflow:hidden} .wh{height:100%!important} .ww{width:100%!important} 

这应该处理任何大小/方向,不仅将resize,但抵消图像。 都没有relativeabsolute定位。

小提琴: http : //jsfiddle.net/filever10/W8aLN/

什么是值得的:现在可以单独使用CSS完成…

新的CSS属性object-fit ( 当前浏览器支持 )

只需设置object-fit: cover;img

你甚至不需要将img包裹在div

小提琴

 img { width: 100px; height: 100px; } .object-fit { display: block; object-fit: cover; } .original { width: auto; height: auto; display: block; } 
 <img src="http://lorempixel.com/413/325/food" width="413" height="325"> <p>Img 'squashed' - not good</p> <img class="object-fit" src="http://lorempixel.com/413/325/food" width="413" height="325"> <p>object-fit: cover - The whole image is scaled down or expanded till it fills the box completely, the aspect ratio is maintained. This normally results in only part of the image being visible. </p> <img class="original" src="http://lorempixel.com/413/325/food" width="413" height="325"> <p>Original ing</p> 

用足够好的浏览器支持(IE8 +),使用带有img标签的背景尺寸封面模拟的纯粹CSS解决scheme:

HTML:

 <div class="container"> <img src="//lorempixel.com/400/200/sports/1/" /> </div> 

CSS:

 .container { position: absolute; top: 0; right: 0; bottom: 0; left: 0; overflow: hidden; } .container img { position: absolute; top: 50%; left: 50%; width: auto; height: auto; max-height: none; max-width: none; min-height: 100%; min-width: 100%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); } 

这个想法是为图像制作额外的包装:

 <div class="wrap"> <div class="inner"> <img src="http://placehold.it/350x150"> </div> </div> 

https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

 cover This keyword specifies that the background image should be scaled to be as small as possible while ensuring both its dimensions are greater than or equal to the corresponding dimensions of the background positioning area. 

所以,你要么在width: 100%height: 100% ,哪一个会在父div产生重叠。 所以我们可以使用下面的逻辑:

 var makeBackgroundCover = function (div) { $(div + " img").css("height", "100%"); if ($(div + " img").width() < $(div).width()) { $(div + " img").css({ "height": "auto", "width": "100%" }); } } 

下面的小提琴显示这个function在水平和垂直的图像上工作。

http://jsfiddle.net/2r5Cb/

另外,对于它的价值,可以通过设置“宽度”和“高度”(设置它们可以打破这个方法)来产生相同的效果:

min-width: 100%; min-height: 100%;

要么

min-width: (your desired percent of viewport width)vw; min-height: (your desired percent of viewport height)vh;

overflow: hidden;

在父母身上

🙂

这是我的方法:

 //collect the nodes var parent = $('.box'); var img = $('image', box); //remove width and height attributes img.removeAttr('width'); img.removeAttr('height'); //set initial width img.attr('width', parent.width()); //if it's not enough, increase the width according to the height difference if (img.height() < parent.height()) { img.css('width', img.width() * parent.height() / img.height()); } //position the image in the center img.css({ left: parseInt((img.width() - parent.width())/-2) + 'px', top: parseInt((img.height() - parent.height())/-2) + 'px' }); 

小提琴

在阅读接受的答案的同时,我们只是testing图像是“肖像”还是“风景”:

  if (ih>iw) {//if portrait 

在OP的情况下,这是正确的。 但其他人可能正在处理矩形,并应考虑到容器和“孩子”形象的纵横比:

  var int_container_width = parseInt( $_container.width() ); var int_container_height = parseInt( $_container.height() ); var num_container_aspect = int_container_width/int_container_height; var int_image_width = parseInt( $_image.width() ); var int_image_height = parseInt( $_image.height()); var num_image_aspect = int_image_width/int_image_height; if ( num_image_aspect > num_container_aspect){ num_scale = int_container_width/int_image_width * 100; } else { num_scale = int_container_height/int_image_height * 100; } 

这是一个纯粹的CSS解决scheme。 你可以定义一个包装器:

 div.cover { position: fixed; top: -50%; left: -50%; width: 200%; height: 200%; } 

和img:

 img.cover { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; min-width: 50%; min-height: 50%; overflow-x: hidden; } 

在这里,现场的例子:

http://codepen.io/ErwanHesry/pen/JcvCw

如果你想让图像在图像中心而不调整图像大小,只需使用下面的代码:

 .box { width: 100px; height: 100px; overflow: hidden; position: relative; } .box img { width: 413px; height: 325px; position: absolute; left: 50%; top: 50%; } 

如果您正在寻找适合的图像大小,请使用以下代码:

 .box { width: 100px; height: 100px; } .box img { width: 100%; height: auto; } 

如果图像宽度比高,这个代码会留下一些空白区域。 如果这两者都不起作用,则可以将图像设置为背景并使用background-size: cover;

对于像我今天所做的一样,在这个问题上发生的任何事情,都可以使用横向,纵向,矩形,方形等图像和任意大小的容器,我在下面列出了自己的代码。

这也将起到响应作用,只要窗口resize,您就需要再次运行它。

JSFiddle

http://jsfiddle.net/66c43ao1/

HTML

 <div class="test"> <div class="cover"> <img src="http://d2ws0xxnnorfdo.cloudfront.net/character/meme/cool-dog.jpg" width="590" height="590"/> </div> </div> 

CSS

 /* modify the width and height below to demonstrate coverage */ .test { height: 300px; position: relative; width: 500px; } /* you will need the below styles */ .cover { height: 100%; left: 0; overflow: hidden; position: absolute; top: 0; width: 100%; z-index: 1; } 

JS

 $('.cover').each(function() { var containerHeight = $(this).height(), containerWidth = $(this).width(), image = $(this).children('img'), imageHeight = image.attr('height'), imageWidth = image.attr('width'), newHeight = imageHeight, newWidth = imageWidth; if (imageWidth < containerWidth) { // if the image isn't wide enough to cover the space, scale the width newWidth = containerWidth; newHeight = imageHeight * newWidth/imageWidth; } if (imageHeight < containerHeight) { // if the image isn't tall enough to cover the space, scale the height newHeight = containerHeight; newWidth = imageWidth * newHeight/imageHeight; } var marginLeft = (newWidth - containerWidth)/2; var marginTop = (newHeight - containerHeight)/2; image.css({ marginLeft : '-' + marginLeft + 'px', marginTop : '-' + marginTop + 'px', height : newHeight, width : newWidth }); }); 

你当然可以使用Backstretch这样的库来做同样的事情,但是我发现这个解决scheme更适合我的目的(不增加依赖性,重量更轻等)。

我创build了一个函数,应该这样做。 我从已接受的答案中借用了一些逻辑,并通过创build图像尺寸的比率来调整它与任何容器一起工作:容器尺寸,然后比较哪一个更大以确定要调整的尺寸。 还添加了一个“中心”参数(“真”中心,假将其设置为上/左)。

我正在用translateX / Y来使用CSS3,但是如果没有它,就可以很容易地使用CSS3。

代码如下:

 var coverImage = function(wrap, center) { if (typeof center === 'undefined') { center = true; } var wr = $(wrap), wrw = wr.width(), wrh = wr.height(); var im = wr.children('img'), imw = im.width(), imh = im.height(); var wratio = wrw / imw; var hratio = wrh / imh; //Set required CSS wr.css({'overflow' : 'hidden'}); im.css({'position' : 'relative'}); if (wratio > hratio) { im.width(wrw); im.css({'height' : 'auto'}); if (center) { im.css({ 'top' : '50%', 'transform' : 'translateY(-50%)' }); } } else { im.height(wrh); im.css({'width' : 'auto'}); if (center) { im.css({ 'left' : '50%', 'transform' : 'translateX(-50%)' }); } } } 

并检出jsfiddle,看看它的行动: https ://jsfiddle.net/cameronolivier/57nLjoyq/2/

我做了一些东西可以模仿背景大小:封面背景位置:中心

如果您想更改位置,只需更改img的“ 顶部 ”和“ 左侧 ”样式

CSS

 .box{ overflow:hidden; position:relative; } .box img{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); } 

JS

 $('.box').each(function() { //aspect ratio of container var boxRatio = $(this).height() / $(this).width(); //aspect ration of image var imageRatio = $(this).children('img').height() / $(this).children('img').width(); //set width or height 100% depend of difference if (imageRatio > boxRatio) { $(this).children('img').css({"width":"100%","height":"auto"}); } else { $(this).children('img').css({"height":"100%","width":"auto" }); } }); 

这个function应该在“load”和“resize”事件中激活。

你可以使用这种风格的图像标签:“object-fit:cover;” 这个链接也会支持你https://css-tricks.com/almanac/properties/o/object-fit/

下面是一个干净的JavaScript函数来实现这个function和一个实现的例子:

 function backgroundCover(elementSizes, containerSizes) { var elementRatio = elementSizes.width / elementSizes.height, containerRatio = containerSizes.width / containerSizes.height; width = null, height = null; if (containerRatio > elementRatio) { width = Math.ceil( containerSizes.width ); height = Math.ceil( containerSizes.width / elementRatio ); } else { width = Math.ceil( containerSizes.height * elementRatio ); height = Math.ceil( containerSizes.height ); } return { width, height }; } 

这是一个实现的例子:

HTML

 <!-- Make sure the img has width and height attributes. The original image's width and height need to be set in order to calculate the scale ratio. --> <div class="photo"><img src="photo.jpg" width="400" height="300"></div> 

CSS

 .photo { position: relative; overflow: hidden; width: 200px; padding-bottom: 75%; /* CSS technique to give this element a 4:3 ratio. */ } .photo img { position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } 

JavaScript的

 $( window ).on( 'resize', function() { $( '.cover-photo' ).each( function() { var img = $( 'img', this ), imgWidth = img.attr( 'width' ), imgHeight = img.attr( 'height' ), containerWidth = $( this ).width(), containerHeight = $( this ).height(), newSizes = backgroundCover( { width: imgWidth, height: imgHeight }, { width: containerWidth, height: containerHeight } ); img.css( { width: newSizes.width, height: newSizes.height } ); } ); } );