簡體   English   中英

如何在盒子的中心插入不同尺寸的圖像?

[英]How can i insert different size image in the center of the box?

如何在框中心插入不同尺寸的圖像? 圖像具有不同的大小。 肖像(高度大於寬度),橫向(寬度大於高度),正方形(寬度與高度相同)和紅色框具有可轉換尺寸。(不僅僅是正方形)

紅色框是可見部分。圖像具有不同的大小,如肖像,風景,正方形

我使用這樣的代碼

HTML

<div class="image">
  <img class="image_insert" src="..">
</div>

CSS

.image{
    position:relative;
    width:100px;
    height:100px;
    overflow:hidden;
}

.image_insert{
    max-width:100%;
    position:absolute;
    margin:auto;
    left:50%;
    -webkit-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    transform:translateX(-50%);
    top:0;
    bottom:0;
  }

JavaScript的

function imageControl(){
 var image = document.getElementsByClassName('image_insert');
 var array = new Array();

 for(var i=0; i<image.length; i++){
  if(image[i].width>image[i].height){
    $(image[i]).css("max-width","none");
    $(image[i]).css("height","100%");
    }
  }
}

有效。 但這種方式取決於文檔(圖像,javascript)加載時間,所以有什么最好的方法在框的中心插入不同大小的圖像? *內部紅盒子里面沒有空的空間!

試試這個。

 .image { position: relative; display: inline-block; } .img-rectangle { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; border: 5px solid #BC2424;; width: 100px; height: 150px; } 
 <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <div class="image"><img src="http://lorempixel.com/300/400/" /><div class="img-rectangle"></div></div> <div class="image"><img src="http://lorempixel.com/400/300/" /><div class="img-rectangle"></div></div> <div class="image"><img src="http://lorempixel.com/400/400/" /><div class="img-rectangle"></div></div> 

你想要的是使用<picture> HTML元素標簽 ,其中包含適用於各種情況的媒體查詢的資源(例如,橫向與肖像,屏幕分辨率/ DPI等)。 然后,瀏覽器將自動加載適當的圖像。

這篇博文應該提供一些關於它們如何使用的附加背景。

使用inline-flex框來對齊圖像,我創建了這個小提琴來顯示用法https://jsfiddle.net/swvdfzax/

CSS將是

div.image{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  border:2px solid red;
  height:60px;
  width:60px;
  vertical-align:top
}
div.image img{
  max-height:100%;
  max-width:100%;
}

而HTML將是

<div class="image"><img src="...path/to/image"></div>

試試這個代碼

 $(function(){ $(".image_insert").each(function(){ var container = $(this).parent(); var img = $(this); img.css({ left: -1 * (img.width()/2 - container.width()/2), top: -1 * (img.height()/2 - container.height()/2) }); }); }); 
 .image{ position:relative; width:200px; height:200px; overflow:hidden; border: 1px solid red; } .image_insert{ position:absolute; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="image"> <img class="image_insert" src="http://lorempixel.com/300/400/"> </div> <div class="image"> <img class="image_insert" src="http://lorempixel.com/400/300/"> </div> <div class="image"> <img class="image_insert" src="http://lorempixel.com/400/400/"> </div> 

這里的JSFiddel演示https://jsfiddle.net/g868ae1h/1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM