指定高度的线性渐变背景

时间:2017-09-28 20:50:29

标签: css

如何为具有指定高度的背景图像添加线性辐射?

Codepen

<div class="bg-img"></div>
<h1>This should not be covered</h1>

html, body {
  width: 100%;
  height: 100%;
}

.bg-img {
  width: 100%;
  height: 60%; # works with 100%, but not anything less
  background: url('http://unsplash.it/1200x800') center center no-repeat;
  background-size: cover;

  &:before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-image: linear-gradient(to bottom right,#002f4b,#dc4225);
    opacity: .6; 
  }
}

1 个答案:

答案 0 :(得分:1)

position:relative添加到.bg-img,因此absolute伪引用它来进行协调和定位。

.bg-img {
  width: 100%;
  height: 60%; # works with 100%, but not anything less
  background: url('http://unsplash.it/1200x800') center center no-repeat;
  background-size: cover;
  position:relative;

https://codepen.io/gc-nomade/pen/ZXKdbv

html,
body {
  width: 100%;
  height: 100%;
}

.bg-img {
  width: 100%;
  height: 60%;
  background: url("http://unsplash.it/1200x800") center center no-repeat;
  background-size: cover;
  position: relative;
}

.bg-img:before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-image: linear-gradient(to bottom right, #002f4b, #dc4225);
  opacity: .6;
}
<div class="bg-img"></div>
<h1>This should not be covered</h1>

其他选项是使用rgba()颜色并将渐变和图像设置为背景图像

html, body {
  width: 100%;
  height: 100%;
}

.bg-img {
  width: 100%;
  height: 60%;
  background:linear-gradient(to bottom right, rgba(0,47,75,0.6), rgba(220,66,37,0.6)), url("http://unsplash.it/1200x800") center center no-repeat;
  background-size: cover;
}
<div class="bg-img"></div>
<h1>This should not be covered</h1>