2016-09-19 118 views
0

你好,我有一個框中有一些內容。我設置了一個幻燈片:before元素來顯示懸停。這個psuedo元素是一個覆蓋整個box設置爲背景圖像的圖像。它可以工作,但它會將框中的內容推到框下方。我喜歡它,所以內容保持在懸停狀態,內容出現在psuedo元素上。防止僞造元素推送內容

.box { 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: #333; 
 
} 
 
.box p { 
 
    color: green; 
 
} 
 
.box:before { 
 
    content: ''; 
 
    background: url('https://ewans.files.wordpress.com/2008/07/grey1.jpg'); 
 
    width: 200px; 
 
    height: 200px; 
 
} 
 
.box:hover:before { 
 
    display: block; 
 
}
<div class="box"> 
 
    <p>content content content</p> 
 
</div>

這裏是的jsfiddle鏈接

jsfiddle

有什麼辦法能有這個僞背景圖像不推內容了嗎?我希望內容保留在psuedo元素頂部的相同位置。 (內容不包含在僞代碼元素中)

另外,您可能會問爲什麼不只是更改懸停框的背景顏色。這是因爲背景圖像是一個自定義圖像,我只是用那個灰色圖像作爲例子。

謝謝

回答

1

這樣做,你在哪裏定位僞絕對。

.box { 
 
    position: relative; 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: #333; 
 
} 
 

 
.box p { 
 
    color: green; 
 
    position: relative; 
 
    z-index: 2; 
 
} 
 

 
.box:before { 
 
    content: ''; 
 
    display: none; 
 
    position: absolute; 
 
    background: url('https://ewans.files.wordpress.com/2008/07/grey1.jpg'); 
 
    top: 0; 
 
    left: 0; 
 
    width: 200px; 
 
    height: 200px; 
 
} 
 

 
.box:hover:before { 
 
    display: block; 
 
}
<div class="box"> 
 
    <p>content content content</p> 
 
</div>

+0

真棒,似乎工作。謝謝。但有什麼方法讓內容出現在元素上?也許與z-index有關? –

+0

真棒謝謝你 –

1

嘗試:

.box{ 
    width: 200px; 
    height: 200px; 
    background-color: #333; 
    position: relative; 
} 

.box:before{ 
    width: 200px; 
    height: 200px; 
    position: absolute; 
    top: 0; 
    left: 0; 
    background: /* your image here */ 
    z-index: -1; 
}