全屏背景视频和混合模式文本的实现
本文转载自:众成翻译
译者:chajn
链接:http://www.zcfy.cc/article/1275
原文:http://thenewcode.com/1136/Fullscreen-Background-Video-with-mix-blend-mode-Overlay-Text?utm_source=CSS-Weekly&utm_campaign=Issue-230&utm_medium=email
我之前谈过网页的全屏背景视频的案例,我还说过如何使用mix-blend-mode属性来创建混合模式的文本,但我从没把两者结合起来,本文由此诞生。
最近时尚网站Everlane展示了这种结合,它触发了我写这篇文章的灵感。首先这里面的代码比起之前的全屏视频要明显简单的多,其次我们假定浏览者使用的也是更新的浏览器(MS Edge还不支持mix-blend-mode
),所以视频背景只能在IE10以上版本中可运行。
HTML代码
我们从 video
开始,加上playsinline
属性,来按序播放(在iOS10系统中允许页内重放),再加上mute
属性 ,以让视频静音。
全屏视频 -> 自动播放的循环视频 -> 不出声。
<video poster="fashion.jpg" playsinline autoplay muted loop>
<source src="fashion.webm" type="video/webm">
<source src="fashion.mp4" type="video/mp4">
</video>
在关联的Codepen中,我加了一个header节点并fixed定位到页面顶端:
<header>
<h1>ZIGGY</h1>
<nav>
<a href="#">Men</a>
<a href="#">Women</a>
<a href="#">Stores</a>
<a href="#">Contact</a>
</nav>
</header>
我在导航项下加入了一些内容,这个文本需要短一些(最好只包含几个词),因为事实证明较长的文本进行混合模式的时候体验很不好:
<div id="fashion">
<h2>There’s a brand new dance but I don’t know its name…</h2>
</div>
CSS代码
video节点要设置绝对定位,根据 object-fit
所述,以设置宽度和高度百分百来覆盖全屏:
video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
注意:视频本身并没有用
fixed
进行定位,以上代码完美适用于内容集中的情况,你怎么移动它都不会超过浏览器窗口的范围。
将body的 margin
为 0
:
body {
margin: 0;
background: #000;
}
hover
时切换标题元素的颜色和背景:
header {
position: fixed;
width: 100%;
text-align: center;
color: white;
transition: .4s;
}
header:hover {
background: rgba(255,255,255,0.8);
color: #000;
}
用flexbox可以将div里的文本始终保持居中,并且会根据窗口大小缩放:
div#fashion {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
中间的文本使用mix-blend-mode: overlay
,用difference
也可以。
h2 {
font-family: Century Schoolbook, Georgia, serif;
margin: 2rem 3rem 0;
mix-blend-mode: overlay;
color: #fff;
}
在关联的CodePen实例中我设定font-size
为vmin
,因为它能和对应的设计完美匹配;我会在下一篇文章中详细探讨vmin和vmax。