2017-01-27 19 views
0

希望這一形象解釋了更多,我想要什麼 bg-pos.png背景的位置是:把左上角的中心

(圖像的透明部分應說明它比.content事業部:-)

較大有一個幾乎保存的方式(最好只是CSS),讓背景圖像開始在中心?

background-position: center top; 

...將使用圖像的中心,而不是左角。

我不能操縱圖像本身(使用透明偏移量),也不能使用絕對值。

+0

爲你需要添加「背景尺寸:包括」 –

+2

這正是的提問者事與願違。 – BoltClock

+1

您必須將'background-position'設置爲一個像素值(在X軸上)。關鍵字或百分比值,我不認爲這是可能的。 – Harry

回答

2

如果不使用絕對值,您將無法在所需元素上使用背景圖像進行此操作。有關原因的說明,請參閱this answer。簡而言之,使用百分比和關鍵字值進行背景定位非常像滑動拼圖,將圖像嚴格限制在元素的背景定位區域內。只有絕對值可以免除這種行爲。

您可以通過將圖像替換爲所需元素的僞元素的背景來進行欺騙,但這需要所需元素相對定位並充當所有絕對定位後代的包含塊,元素:

.content { 
 
    position: relative; 
 
    height: 200px; 
 
    border: 1px solid; 
 
} 
 

 
.content#one { width: 100px; } 
 
.content#two { width: 200px; } 
 

 
.content::before { 
 
    content: ''; 
 
    position: absolute; 
 
    left: 50%; 
 
    width: 50%; 
 
    height: 100%; 
 
    background: url(http://placehold.it/150x150) no-repeat; 
 
}
<div class="content" id="one"></div> 
 
<div class="content" id="two"></div>

0

可與僞元素來完成

.cimg { 
 
    border: 1px solid black; 
 
    height: 400px; 
 
    position: relative; 
 
} 
 

 
.cimg::after { 
 
    content: ""; 
 
    position: absolute; 
 
    left: 50%; 
 
    top: 0; 
 
    height: 100%; 
 
    width: 50%; 
 
    background-image: url("http://www.youramazingplaces.com/wp-content/uploads/2014/06/sunset-5.jpg"); 
 
    background-repeat: no-repeat; 
 
    background-size: 400px; 
 
}
<div class="cimg"> 
 

 
</div>