2016-09-19 124 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; 
}