2016-04-21 44 views
-1

我想顯示中心下面的圖片:製作左,右頁邊距等於當外部組件是不知道

enter image description here

我有以下樣式項:

var itemStyle = { 
    display: 'block', 
    width: this.computeWidth(), 
    height: '250px', 
    backgroundImage: 'url(' + imageLocation + ')', 
    backgroundPosition: 'center !important', 
    backgroundSize: 'cover', 
    boxShadow: '10px 10px 5px #888888', 
    borderRadius: '15px', 
    marginLeft: 'auto !important', 
    marginRight: 'auto !important' 
}; 

其中我展示像這樣:

<div style={itemStyle}> 
</div> 

this.computeWidth()是該方法中,其中我調整取決於頁面上的圖像的寬度:

computeWidth: function() { 
    console.log("this.state.window.width: " + this.state.window.width); 
    if(this.state.window.width > 350) { 
     return '250px'; 
    } 
    return Math.floor(0.7 * this.state.window.width).toString() + 'px'; 
    }, 

我也嘗試使用這種方法計算marginLeftmarginRight

computeMargin: function() { 
     if(this.state.window.width > 350) { 
     return 'margin-auto'; 
     } 
     return Math.floor(0.15 * this.state.window.width).toString() + 'px'; 
    }, 

然而,圖像沒有被再次居中。

所以,我怎麼能確保圖像是中央的頁面?(最好不改變包含它的組件的css

+0

你定位元素或** **背景 - 圖像,其並不清楚。居中元素有**數千**您可能會檢查的相關問題。 –

+0

'backgroundImage'。但它是一回事,不是嗎?因爲背景圖片佔據了整個元素。 – octavian

回答

1

這有什麼錯margin: Xpx auto?它應該工作,因爲圖像定義寬度。或者,也可以爲了增加flexbox性質的母體居中孩子:

.parent { 
    display: inline-flex; 
    justify-content: center; 
    width: 100%; 
} 
0

CSS應該足以解決這個問題。將圖片包裹在div中,並以保證金屬性爲中心。

<div class="img-wrap"> 
    <img src="foo.jpg"> 
</div> 

.img-wrap { margin: 0 auto; } 

這裏指的更多的細節:CSS-Tricks centering guide


編輯 - 爲中心的背景圖像應用以下CSS到div:

background-image: url("foo.jpg"); 
background-position: 50% 50%; 
background-repeat: no-repeat; 
background-size: contain; /* Full image in div, no cropping, preserve aspect ratio */ 

這使圖像的中心沿着div中的兩個軸(x和y)中途移動圖像的中心。因此,完美的集中。


或者,用這個英雄圖片:

background-size: cover;  /* Fill div (even if img is cropped), preserve aspect ratio */ 

更多背景定心:Sitepoint: background-position property

+0

我需要保持圖像爲背景。 – octavian

相關問題