如何在柔性盒中使用透明覆盖层和中心?

时间:2015-08-05 17:30:28

标签: html css flexbox

我有一个带有背景图片的块元素。我试图:

  • 在背景图片上添加透明渐变叠加层
  • 使用flexbox中心另一个块元素

已经相互独立地实现了这两个,请参阅CodePen以及下面的图片和代码。

使用透明覆盖(删除子块HTML):

enter image description here

居中子块(删除了叠加CSS):

enter image description here

然而,当我尝试组合效果时,flexbox停止工作并且子块周围缺少叠加层enter image description here

这是我的HTML

<div class="container">
  <p>title goes here</p>
</div> 

这是我的CSS:

.container {
  background: url("http://msue.anr.msu.edu/uploads/images/forest.jpg");
  height: 400px;
  width: 100%;
  box-shadow: inset 0px -4px 14px 0px rgba(50, 50, 50, 0.71);
  background-size: 100% auto;
  z-index: 0;
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.container p {
  display: block;
  color: red;
  text-align: center;
  font-size: 24pt;
  background-color: blue;
  z-index: 2;
}
.container:after {
  content: '';
  background: linear-gradient(135deg, #dc4225, #292484);
  width: 100%;
  height: 100%;
  opacity: 0.5;
  top: 0;
  left: 0;
  display: block;
  z-index: 1;
  position: relative;
}

如何同时进行半透明叠加叠加和弹性框?

2 个答案:

答案 0 :(得分:3)

对于.container:after,请将position: relative更改为position: absolute

直播,工作示例:

&#13;
&#13;
.container {
  background: url("http://msue.anr.msu.edu/uploads/images/forest.jpg");
  height: 400px;
  width: 100%;
  box-shadow: inset 0px -4px 14px 0px rgba(50, 50, 50, 0.71);
  background-size: 100% auto;
  z-index: 0;
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.container p {
  display: block;
  color: red;
  text-align: center;
  font-size: 24pt;
  background-color: blue;
  z-index: 2;
}
.container:after {
  content: '';
  background: linear-gradient(135deg, #dc4225, #292484);
  width: 100%;
  height: 100%;
  opacity: 0.5;
  top: 0;
  left: 0;
  display: block;
  z-index: 1;
  position: absolute;
}
&#13;
<div class="container">
  <p>title goes here</p>
</div> 
&#13;
&#13;
&#13;

Codepen版本:http://codepen.io/anon/pen/gpqxoo

答案 1 :(得分:1)

如果人们需要像我一样将容器的位置设置为绝对:

.container {
    @include inline-flex;
    @include flex-direction(column);
    @include align-items(center);
    @include justify-content(center);

    background-position: center center;
    background-repeat: no-repeat;
    background-size: contain;
    font-size: 16px;
    height: 100%;
    width: 100%;
    position: absolute;
    white-space: normal;
    z-index: 1;
}

.container::after {
    content: ' ';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0,0,0,.8);
    z-index: -1;
}

此处的重要性部分为rgbaz-index。容器的背景图像是在代码中动态设置的,但这里并不相关。