2017-08-10 68 views
0

我试图添加具有模糊效果的背景要素(这里看到)背景元素越过正文元素

.background-image { 
    position:absolute; 
    left:0; 
    right:0; 
    top:0; 
    bottom:0; 
    background-image: url('bg.jpg'); 
    background-size: cover; 
    display: block; 
    filter: blur(5px); 
    -webkit-filter: blur(5px); 
    height: 800px; 
    left: 0; 
    position: fixed; 
    right: 0; 
    z-index: 100; 
} 

然而,当我把它放在我的HTML:

<body> 
    <main> 
     <div> 
     <div class="background-image"></div> 

      <div class="homestrip"> 
       <!-- rest of stuff goes here --> 

背景重叠一切。我看不到我的身体元素,无论我移动背景图像元素的位置,我的其他东西都不可见。

回答

1

给出背景元素为负的z-index将其置于其父项下。

.background-image { 
 
    position: absolute; 
 
    left: 0; 
 
    right: 0; 
 
    top: 0; 
 
    bottom: 0; 
 
    background-image: url('http://lorempixel.com/1200/1200'); 
 
    background-size: cover; 
 
    display: block; 
 
    filter: blur(5px); 
 
    -webkit-filter: blur(5px); 
 
    height: 800px; 
 
    left: 0; 
 
    position: fixed; 
 
    right: 0; 
 
    z-index: -1; 
 
} 
 

 
body { 
 
    color: yellow; 
 
}
<div class="background-image"> 
 
</div> 
 

 
<h1>Text over image</h1>

一个更好的选择是使用伪元件代替标记:

body::before { 
 
    position: absolute; 
 
    left: 0; 
 
    right: 0; 
 
    top: 0; 
 
    bottom: 0; 
 
    background-size: cover; 
 
    display: block; 
 
    filter: blur(5px); 
 
    -webkit-filter: blur(5px); 
 
    height: 800px; 
 
    left: 0; 
 
    position: fixed; 
 
    right: 0; 
 
    z-index: -1; 
 
    content: url('http://lorempixel.com/1200/1200'); 
 
} 
 

 
body { 
 
    color: yellow; 
 
}
<h1>Text over image</h1>