2010-07-27 74 views
24

使用plain <img>標籤有可能以與CSS背景圖像和背景位置相同的方式偏移圖像嗎?在<img>中偏移可見圖像標籤的方式與背景圖像相同

有在頁面上主圖像和它意義不大有單獨的縮略圖時都將被加載(從而增加帶寬)。一些圖像是肖像,有些是風景,但是我需要顯示以均勻的大小的縮略圖(和剪切掉多餘的,其中它不能滿足期望的縱橫比)。

雖然使用其他標籤和背景CSS值可以使用普通<img>標籤。

回答

18

不幸的是沒有,這是不可能的,只有一個<img>標籤。有2個解決方案,我能想到的,您的問題:

<div class="thumbnail" style="background: url(an-image.jpg) no-repeat 50% 50%"></div> 

CSS:在圖像作爲背景圖片屬性應用於

CSS背景圖像

創建<div>剪輯

使用clip-path屬性僅顯示圖像的一部分:

<!-- Clip properties are top, right, bottom, left and define a rectangle by its top-left and bottom-right points --> 
<div style="clip-path: inset(10px 200px 200px 10px)"> 
    <img src="an-image.jpg"> 
</div> 

您可以閱讀更多關於它in this article

+0

CSS夾做的伎倆(甚至圖片)謝謝! – Metalshark 2010-07-28 07:34:46

+0

錯誤的做法。至少,如果您將您的內容發送到HOTMAIL帳戶。 Hotmail只顯示圖像,而不是圖像的div。一個簡單的方法是使用本地img屬性剪輯:rect(0px,100px,100px,0px)。很簡單。只是不要把它放在溢出:隱藏的div。在w3schools上查看房產。 – Otvazhnii 2015-07-06 13:48:08

+0

要小心,支持'clip-path' [很弱](https://caniuse.com/css-clip-path/embed) – 2017-11-23 13:15:24

6

如果你把圖像在一個div你可以使用利潤來移動圖像。這個特殊的例子使用一個精靈圖片標誌作爲改變懸停位置的主頁鏈接。您也可以跳過A標籤並使用#logo img上的邊距屬性移動圖像。

的HTML:

<div id="logo"> 
    <a href="#"> 
     <img src="img/src.jpg" /> 
    </a> 
</div> 

的CSS:

#logo { 
    display: block; 
    float: left; 
    margin: 15px 0; 
    padding: 0; 
    width: 350px; //portion of the image you wish to display 
    height: 50px; //portion of the image you wish to display 
    overflow: hidden; //hide the rest of the image 
} 
#logo img { 
    width: 350px; 
    height: 100px; // you'll see this is 2x the height of the viewed image 
    padding: 0; 
    margin: 0; 
} 
#logo a { 
    display: block; 
    float: left; 
    margin: 0; 
    padding: 0; 
} 
#logo a:hover { 
    margin-top: -50px; //move up to show the over portion of the image 
} 

希望幫助!

3

之前

<img src="img.png"> Text, Links, Etc 

後:

<img src="img.png" style="float:left; margin-bottom:-5px"> Text, Links, Etc 

閱讀關於W3C塊格式化的內容。

+1

你是對的。 'quid'的答案是矯枉過正。在我的情況下,即使是「float:left」也沒有必要。簡單的負邊界調整就是將元素的查看區域向左或向右滑動所需的全部內容 - 但可能需要與img標記的高度/寬度尺寸結合使用。一個小提琴(或堆棧片段)將是這個答案的好主意。 – gibberish 2016-02-05 01:20:07

0

某些圖像是縱向的,有些是橫向的,但是我需要以統一的尺寸顯示縮略圖(並裁剪多餘部分以達到所需的縱橫比)。

使用background-size: cover這應該exactly solve that problem→與good browser support

並讓你圖片的背景(可能使用background-image作爲內嵌樣式):

<img style="background-image: url('img/foo.png')"/>