2015-11-02 52 views
0

我嘗試在框架內設置圖像。如何將任何大小的圖像放在框架中間

風格

#wrapper { 
     border: 2px solid black; 
     width: 600px; 
     height: 400px; 
     overflow:hidden; 
     position: relative; 
     display: inline-block; 
    } 
    img{ 
     position: absolute; 
     height:auto; 
    } 

HTML

<div id="wrapper"> 
    <img src="http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg" alt="our img" /> 
</div> 
<br> 
<div id="wrapper"> 
    <img src="http://7-themes.com/data_images/out/42/6914793-tropical-beach-images.jpg" alt="our img" /> 
</div> 

有沒有什麼辦法,以確保圖像顯示在像this框的中間?

回答

0

你可以這樣做:

使用transform垂直和水平居中圖像

CSS

img{ 
     position: absolute; 
     height:auto; 
     top: 50%; 
     left: 50%; 
     -webkit-transform: translate(-50%,-50%); 
     transform: translate(-50%,-50%); 
    } 

DEMO HERE

+0

感謝您的幫助! – Song

1

事情是這樣的:

#wrapper { 
 
     border: 2px solid black; 
 
     width: 600px; 
 
     height: 400px; 
 
     overflow:hidden; 
 
     position: relative; 
 
     display: inline-block; 
 
     text-align:center; 
 
    } 
 
img{ 
 
     max-width: 100%; 
 
}
<div id="wrapper"> 
 
    <img src="http://www.gettyimages.co.uk/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg" alt="our img" /> 
 
</div> 
 
<br> 
 
<div id="wrapper"> 
 
    <img src="http://7-themes.com/data_images/out/42/6914793-tropical-beach-images.jpg" alt="our img" /> 
 
</div>

0

這將圍繞你的img

img{ 
    display:block; 
    position: absolute; 
    height:auto; 
    margin:0 auto; 
} 
0

這裏是我的建議:

#wrapper { 
    text-align:center; 
    border: 2px solid black; 
    width: 600px; 
    height: 400px; 
    overflow:hidden; 
    position: relative; 
} 
img{ 
    display: inline-block; 
    height:auto; 
    position: relative; 
    top: 50%; 
    -webkit-transform: translateY(-50%); 
    -ms-transform: translateY(-50%); 
    transform: translateY(-50%); 
} 

而且工作jfiddle:https://jsfiddle.net/o0efwd20/

相關問題