前言
好几年没有写过官网,最近写了一个,竟然发现background的用法都生疏了。
需求
大概就是这样,有背景图 有背景渐变。
实现
上来就是定位,看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
text-align: center;
}
.bg {
position: relative;
height: 100vh;
background-image: linear-gradient(red, blue);
}
.bg-img {
position: absolute;
}
.bg-l {
width: 258px;
height: 320px;
top: 120px;
left: 40px;
background: url('./left.png') no-repeat center;
}
.bg-r {
width: 222px;
height: 174px;
top: 180px;
right: 60px;
background: url('./right.png') no-repeat center;
}
.bg-cont {
position: relative;
}
</style>
</head>
<body>
<div class="bg">
<div class="bg-img bg-l"></div>
<div class="bg-img bg-r"></div>
<div class="bg-cont">
<div>左右两侧有背景图</div>
<div>
还有一定高度的背景渐变
</div>
<div>
<h1>header</h1>
</div>
<div>
其他内容
</div>
</div>
</div>
<div>
<p>其余内容</p>
</div>
</body>
</html>
既然是官网,可能是需要改来改去的。然后我发现,每次替换图片我都需要修改bg的高度和图片div大小,很不方便。
心里隐隐约约的老是觉得我有点滥用定位了。
好像记得background可以写多组的。去mdn上看看background文档 后,又修改一版
实现2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
text-align: center;
}
.bg {
height: 100vh;
background: url('./left.png') no-repeat 180px 40px, url('./right.png') no-repeat calc(100vw - 280px) 180px, linear-gradient(red, blue);
/* 还可以灵活指定图片大小 */
/* background-size: 30px auto, 40px auto, auto auto; */
}
</style>
</head>
<body>
<div class="bg">
<div>左右两侧有背景图</div>
<div>
还有一定高度的背景渐变
</div>
<div>
<h1>header</h1>
</div>
<div>
其他内容
</div>
</div>
<div>
<p>其余内容</p>
</div>
</body>
</html>
总结
长时间不用,略有生疏,还好有点印象。不太确定的时候就去看官网。