html - 如何在背景速记中实现 CSS 模糊?

标签 html css background blur shorthand

目标是模糊背景而不模糊其上方的所有其他元素。

对于背景和内容使用单独的 div 并依赖 z-indexes 的方法对我来说有点不灵活,所以我想知道是否可以在背景中实现 CSS 模糊滤镜 shorthand 语法(因为“background-filter: blur(5px)”不是有效的 CSS),它只会将其应用于背景。

Tesla用速记符号做得很好,但他们使用透明/黑色渐变,而我想使用模糊。这是我尝试过的一些基于 Tesla 登录页面的简化代码:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="the-CSS-Written-Below">
    </head>
    <body class="background-image">
        <div style="background-color: yellow">
            <p>Some text that shouldn't be blurred!</p>
        </div>
    </body>
</html>

CSS:

.background-image{
    background: radial-gradient(transparent, hsl(0, 0%, 2%)), gray url(http://leecamp.net/wp-content/uploads/kitten-3.jpg) no-repeat center center fixed;
}

这是一个 JSFiddle这样您就可以看到它的样子。

然后当我尝试将速记过滤器从径向渐变更改为模糊时,它停止工作:

CSS:

.background-image{
    background: blur(5px), gray url(http://leecamp.net/wp-content/uploads/kitten-3.jpg) no-repeat center center fixed;
}

我不确定这里的模糊语法是否不正确/速记需要不同,或者这可能是完全错误的处理方式。甚至可以像这样用速记模糊吗?

最佳答案

问题是 blur 不是 background 属性的值,而是 filter 的值。根据Mozilla :

The background CSS property is a shorthand for setting the individual background values in a single place in the style sheet. background can be used to set the values for one or more of: <background-clip>, <background-color>, <background-image>, <background-origin>, <background-position>, <background-repeat>, <background-size>, and <background-attachment>.

Tesla 可以使用 background-gradient 因为 background-image 属性 can have因为它的值(value)观:

<bg-image>#
where <bg-image> = none | <image>
where <image> = <url> | <image()> | <image-set()> | <element()> | <cross-fade()> | <gradient>

要完成您想要的,需要 2 个 div,如下所示:

.background-image {
    background: gray url(http://leecamp.net/wp-content/uploads/kitten-3.jpg) no-repeat center center fixed;
    position: fixed;
    top:0;
    left:0;
    width:100vw;
    height:100vh;
    z-index:0;
    filter:blur(5px);
}
<body>
    <div class="background-image"></div>
    <div style="background-color: yellow;position:relative;">
        <p>Some text that shouldn't be blurred!</p>
    </div>
</body>

请注意,您必须将 position:relative 添加到您的其他 div,以便它显示在 background-image div 之上。

我使用了 CSS3 vw (view-width) 和 vh (view-height) 来强制 background-image< 的宽度和高度 div,但您可以改用 %

关于html - 如何在背景速记中实现 CSS 模糊?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45603203/

相关文章:

javascript - 使用帖子循环将 Wookmark tile 插件应用于 wordpress 主题

html - 媒体查询 : "when width>2.5*height"

html - 背景修复和溢出-y :scroll

html - 背景属性不工作 CSS3

javascript - 获取 Anchor 的下一个元素

html - 背景图像模糊 - css

javascript - 如何破解 LiveScript 以链接 html 中的单独文件

javascript - 使用 javascript 生成用户 ID 并将其显示在文本框中

css - 在 Twitter Bootstrap 中更改导航栏颜色

html - 如何使用CSS添加居中背景