预览效果:
其中,最关键的属性:object-fit: cover;
语法:
object-fit: fill|contain|cover|scale-down|none|initial|inherit;
详细语法如下:
值 | 描述 |
---|---|
fill | 默认,不保证保持原有的比例,内容拉伸填充整个内容容器。 |
contain | 保持原有尺寸比例,使图片的宽度完整的显示,高度自动缩放。 |
cover | 保持原有尺寸比例,高度铺满容器,宽度等比缩放,超出部分被剪切 |
none | 保留原有元素内容的长度和宽度,超出部分被剪掉,保留下来的内容使图片的正中央 |
scale-down | 保持原有尺寸比例,当图片实际宽高小于所设置的图片宽高时,显示效果与none一致;否则,显示效果与contain一致 |
完整代码如下:
HTML部分:
<body>
<div class="video-box">
<video class="video-background" preload="auto" loop playsinline autoplay muted src="xd.mp4"
tabindex="-1"></video>
<div class="layer">
<img src="https://cs.xidian.edu.cn/images2020/logo02.png" alt="xd_logo" />
<div class="slogan">
<div class="subtitle">西安电子科技大学2021招生宣传片</div>
<div class="title">厚德、求真、砺学、笃行</div>
<div class="try-btn" onclick="postNow()">立即报名</div>
</div>
</div>
</div>
<div class="content">
<div class="avatar-box">
<img class="avatar" src="https://profile.csdnimg.cn/F/3/C/1_qq_42691298" alt="不想学习的打工人">
<p class="nickname">CSDN-不想学习的打工人~</p>
</div>
</div>
<script>
function postNow() {
location.href = 'https://www.xidian.edu.cn/'
}
</script>
</body>
注意:在谷歌浏览器中,要想实现视频自动播放,必须要在autoplay基础上加上muted属性
CSS部分:
* {
margin: 0;
padding: 0;
}
body {
font-family: Gilroy Semi Bold, -apple-system, BlinkMacSystemFont, Segoe UI, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Helvetica Neue, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol;
}
.video-box {
position: relative;
height: 100vh;
background-color: #C1CFF7;
/*进行视频裁剪*/
overflow: hidden;
}
.video-box .video-background {
position: absolute;
left: 50%;
top: 50%;
/*保证视频内容始终居中*/
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
object-fit: cover;
min-height: 800px;
}
.layer {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(19, 60, 154, .2);
}
.layer img {
margin-top: 15px;
margin-left: 100px;
}
.slogan {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 684px;
color: white;
text-align: center;
}
.slogan .subtitle {
font-weight: 550;
font-size: 20px;
letter-spacing: 10px;
margin: 0 0 16px;
}
.slogan .title {
font-weight: 550;
font-size: 56px;
margin: 0 0 16px;
}
.slogan .try-btn {
position: relative;
left: 50%;
width: 156px;
height: 54px;
line-height: 54px;
margin-top: 40px;
margin-left: -78px;
color: #3370ff;
background: white;
text-align: center;
border-radius: 100px;
font-weight: 600;
cursor: pointer;
}
.content {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100vh;
background-color: black;
}
.content .avatar-box {
display: flex;
justify-content: space-between;
align-items: center;
color: white;
}
.content .avatar-box .avatar {
width: 80px;
height: 80px;
border-radius: 50%;
margin-right: 25px;
}
.content .avatar-box .nickname {
font-size: 35px;
font-weight: 550;
}