Realization of Background Ambiguity in CSS Settings

Time:2019-5-30

In order to make the page look better, we often need to set some background pictures, but when the background pictures are too fancy, it will affect our main content, so we need to use the filter attribute to set its blurred value.

The HTML code is as follows

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="cover">
  <h1> I am the content that needs to be highlighted.
</div>
</body>
</html>

But if it’s used directly in the background picture,


.cover{
    width:600px;
    height:300px;
    position:relative;
    text-align:center;
    line-height:300px;
    color:white;
    background:transparent url(https://91jean.oss-cn-hangzhou.aliyuncs.com/18-8-31/16567303.jpg) center center no-repeat;
    filter:blur(5px);
    background-size:cover;
}

This may result in the following situation.

We will find that both the background and the main content are blurred.

Solution: Add a pseudo-element to the background image, and set the background image and filter attributes on the pseudo-element, the specific code is as follows


.cover{
    width:600px;
    height:300px;
    position:relative;
    text-align:center;
    line-height:300px;
    color:white;
}

.cover::before{    
    content:'';
    position:absolute;
    top:0;
    left:0;
    width:600px;
    height:300px;
    background:transparent url(https://91jean.oss-cn-hangzhou.aliyuncs.com/18-8-31/16567303.jpg) center center no-repeat;
    filter:blur(5px);
    z-index:-1;
    background-size:cover;
}

summary

Above mentioned is the implementation method of CSS setting background ambiguity introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support to developpaer.