2013-06-06 39 views
4

我正在致電差距。所以,我需要以通用格式提供代碼,以便適用於任何設備。如何在任何設備的中心放置圖像?

我有尺寸的圖像,尺寸爲2350 * 180

我試圖與這些代碼..

width: 100%; 
top: 100%; 
margin-top: 50%; 

但是,這些並不在該中心的各種設備。

然後我用

vertical-align: middle; 

然後

display: block; 
text-align: center; 

然後

<table> 
    <tr style="vertical-align: middle;"> 
     <td id="main" style="width: 100%;"> 
      <img src="" /> 
     </td> 
    </tr> 
</table> 

嘗試了所提到的所有上述CSS,我的輸出---->圖像棍棒屏幕頂部的頂部邊距如果我給了margin-top:0;

請幫助我,糾正我。

我有2個問題相對於這個大圖像

現在,我有一個背景圖像

style="background:url("img/bg.png") no-repeat fixed center top; width:100%; height:100%; " 

這個代碼適用於只有少數..是否有任何錯誤我的代碼?

第二個問題,當我滾動那裏是可見的滾動條。所以我添加了

style="overflow:hidden;" 

<img src=""/> tag. 

我是否正確或應該添加任何其他代碼?

+0

是否可以將圖像用作實際的背景圖像或是否必須是「」?然後你可以使用'background:url(/ * image-path/img.png * /)no-repeat center center;' – kleinfreund

+0

我在該圖像上使用了**映射功能**。現在,@ kleinfreund請指導我是否可以使用它作爲背景圖片? – user

+1

您不能在背景圖像上使用圖像映射。 (我昨天試過類似的東西:<) – kleinfreund

回答

3

這工作 - 不要忘了圖像的URL添加到src屬性。 你也可以使用div而不是你的表格。

HTML:

<table> 
    <tr> 
     <td> 
      <img src="" /> 
     </td> 
    </tr> 
</table> 

CSS:

body, html { 
    height: 100%; 
    margin: 0; 
} 

table { 
    width: 100%; 
    height: 100%; 
    text-align: center; 
} 

img { 
    max-width: 100%; 
    vertical-align: middle; 
} 

注意:如果你有你的周圍表父元素,你需要添加height: 100%;到他們。

+0

不,它沒有工作...: - ( – user

+0

@user這是可行的,用一個新的jsfiddle.net/codepen.io嘗試一下,如果它不適合你,你的代碼中會有一些與你的代碼有衝突的地方 – kleinfreund

+0

這就是我如何得到它http:/ /jsfiddle.net/Ztru7/2/ – user

4

添加max-width:100%圖像,並將其放置在表的height:100%

body, html{ 
    height:100%; 
    margin:0; 
    padding:0 
} 
table{ 
    height:100%; 
    background:#fffad6; 
} 
img{ 
    max-width:100%; 
} 

DEMO

+0

在img上你不需要'height:auto;'以保持屏幕尺寸的比例嗎? – kleinfreund

+1

@kleinfreund NO。最大寬度將妥善保管 – Sowmya

+0

你是對的。但是單獨使用你的代碼,圖像就不是以horicontally爲中心的。你需要'width:100%;'在桌子上以及'text-align:center;' – kleinfreund

2

我做了一些挖掘周圍,這就是我想出了寬度居中水平和垂直一個形象:http://jsfiddle.net/jdtjk/2/

CSS:

.middle{ 
    position:absolute; 
    top:0; 
    bottom:0; 
    right: 0; 
    left: 0; 
    margin: auto; 
} 

HTML:

<div> 
    <img src="*" class="middle" /> 
</div> 

編輯:

更改縮小圖像以適應窗口大小: http://jsfiddle.net/jdtjk/5/

更改CSS:

.middle{ 
    position:absolute; 
    top:0; 
    bottom:0; 
    right: 0; 
    left: 0; 
    margin: auto; 
    max-width: 100%; 
    max-height: 100%; 
    height: auto; 
    width: auto; 
} 

如果你想限制上升/低檔次可以在你使用的CSS最小寬度最小高度屬性。如果要升級圖像,可以更改最大屬性。

+0

這使圖像居中,正確。但是如果窗口像圖像本身一樣小,它將不會調整大小。雖然我不確定這是否有必要。 – kleinfreund

+1

檢查編輯的答案和現在鏈接到JS提琴手:)這應該調整圖像的大小以適應屏幕。 –