中央文本在覆盖正方形中没有不透明度



我创建了一个具有背景图像的正方形,我用额外的div叠加了它,在该div的顶部,我想拥有文本。现在,我认为我可以使用z-indexposition: relative正确地将其正确处理,但它不起作用。目标是将文本放在黑色覆盖层的顶部。

请记住,我不想降低文本的不透明度。

这是我的代码,有关演示,请参阅此处的jsfiddle

.image-holder {
  width: 275px;
  height: 274px;
  display: inline-block;
  position: relative;
  z-index: 13;
  background-color: blue;
  margin-left: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
}
h2.offer-image-title {
  color: red;
  border: 0;
  text-align: center;
  font-size: 36px;
  display: inline-block;
  padding: 0;
  margin: 0;
  padding-top: 32%;
  position: relative;
  z-index: 15;
}
.offer-image {
  width: 100%;
  height: 100%;
  position: relative;
}
.offer-1 {
  background-image: url(http://www.wnd.com/files/2015/03/chuck_norris300x300-275x275.jpg);
}
.overlay-black {
  background-color: black;
  opacity: 0.5;
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 14;
}
<div class="image-holder">
  <div class="offer-image offer-1">
    <div class="overlay-black"></div>
    <h2 class="offer-image-title">Chuck Norris</h2>
  </div>
</div>

您的H2需要绝对定位和顶部/左定位:

h2.offer-image-title {
 color: red;
 border: 0;
 text-align: center;
 font-size: 36px;
 display: inline-block;
 padding: 0;
 margin: 0;
 padding-top: 32%;
 position: absolute;
 z-index: 15;
 top: 0px;
 left: 0px;
}

您可以将 linear-gradient() rgba()与背景图像一起使用,并用flexbox中心。

.image-holder {
  width: 200px;
  height: 200px;
  background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url(https://i.stack.imgur.com/rFpk9.jpg);
  background-size: 100%, cover;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}
<div class="image-holder">
  <h2>Chuck Norris</h2>
</div>

我创建了一个正方形,它具有背景图像,我覆盖了一个额外的层,在该div上,我想拥有文本。

一种解决方案是让您的h2 SIT 内部嵌套的div

.image-holder{
	width:275px;
	height:274px;
	display:inline-block;	
	position:relative; 
	z-index:13;
	background-color:blue;
	margin-left:20px;
	margin-right:20px;
	margin-bottom:20px;
}
h2.offer-image-title{
    width: 100%;
	color:red;
	border:0;
	text-align:center;
	font-size:36px;
	display:inline-block;
	padding:0;
	margin:0;
	padding-top:32%;	
	position:relative;
	z-index:15;
}
.offer-image{
	width:100%;
	height:100%;
	position:relative;
}
.offer-1{	
	background-image: url(http://www.wnd.com/files/2015/03/chuck_norris300x300-275x275.jpg);
}
.overlay-black{
	background-color: rgba(0, 0, 0, 0.5);
	position:relative;
	top:0;
	left:0;
	width:100%;
	height:100%;
	z-index:14;
}
<div class="image-holder">
  <div class="offer-image offer-1">							
    <div class="overlay-black">
      <h2 class="offer-image-title">Weight lifting</h2>
    </div>					
  </div>
</div>

edit :在看到您对另一个答案的评论后,我从内部div删除了opacity规则,而是使用background-colorrgba值来实现相同的结果,但不会影响其不透明度h2。另外,将width:100%添加到h2将使text-align: center工作。

最新更新