[英]How to emulate background-size: cover on <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
。 但是,什么公式可以使我獲得合適的圖像新尺寸以及左+頂部位置?
值得一提的是:現在,僅需使用CSS,就可以...
只需設置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>
您可以在此webplatform文章中了解有關此新屬性的更多信息。
另外,這是上面文章的一個小提琴 ,它演示了object-fit
屬性的所有值。
足夠接近的純CSS解決方案,用於使用img標簽進行背景尺寸封面模擬,並具有很好的瀏覽器支持(IE8 +):
.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="container"> <img src="//lorempixel.com/400/200/sports/1/" /> </div>
這可能更容易
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}
這應該可以處理任何大小/方向,不僅可以調整大小,還可以偏移圖像。 全部沒有relative
或absolute
定位。
開了個小提琴: http : //jsfiddle.net/filever10/W8aLN/
同樣,就其價值而言,也可以通過設置“ width”和“ height”(設置它們可能會破壞這種方法)來產生相同的效果:
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;
在父母
:)
這個想法是為圖像做額外的包裝:
<div class="wrap"> <div class="inner"> <img src="http://placehold.it/350x150"> </div> </div>
並使用這樣的CSS:
.wrap { position: relative; width: 100%; height: 200px; background: rgba(255, 0, 0, 0.3); overflow: hidden; } .inner { position: absolute; min-width: 100%; height: 100%; left: 50%; -moz-transform: translateX(-50%); -o-transform: translateX(-50%); -ms-transform: translateX(-50%); -webkit-transform: translateX(-50%); transform: translateX(-50%); } .inner img { position: absolute; min-height: 100%; min-width: 100%; top: 50%; left: 50%; -moz-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }
這是工作示例: https : //jsfiddle.net/kr60jroe/
從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%"
});
}
}
下面的小提琴顯示了此功能在水平圖像和垂直圖像上的作用。
這是我的方法:
//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'
});
在閱讀接受的答案時,令我驚訝的是,我們僅測試圖像是“人像”還是“風景”:
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解決方案。 您可以使用以下方法定義包裝器:
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;
}
這是現場示例:
您可以對圖片標簽使用這種樣式:“ object-fit:cover;” 此鏈接還將為您提供支持https://css-tricks.com/almanac/properties/o/object-fit/
這是執行此操作的干凈JavaScript函數以及實現示例:
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
} );
} );
} );
如果您希望圖像在框中居中而不調整圖像大小,請使用以下代碼:
.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;
。
對於今天遇到這種答案的任何人,就像我今天在尋找一種適用於橫向,縱向,矩形,正方形等圖像以及任意容器大小的解決方案一樣,我在下面提供了自己的代碼。
這也將以響應方式工作,只要窗口調整大小,您只需要再次運行即可。
JSFiddle :
的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之類的庫來執行相同的操作,但是我發現此解決方案對於我的目的來說是更好的(不增加依賴關系,減輕重量等)。
我在下面創建了一個應該執行的功能。 我從可接受的答案中借用了一些邏輯,並通過為圖像尺寸創建一個比率來調整它以與任何容器一起使用:容器尺寸,然后進行比較以找出調整尺寸。 還添加了“居中”參數(“ true”居中,false將其設置為頂部/左側)。
我將CSS3與translateX / Y結合使用,但如果沒有它,就可以使其正常工作。
這是代碼:
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/
我做了一些可以模仿background-size:cover和background-position:center的工作 。
如果要更改位置,只需更改img的樣式“ top ”和“ left ”
的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" });
}
});
應在“加載”和“調整大小”事件時激活此功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.