将文字放在图像上

Putting the text on image

无法解决此问题。尝试了不同的东西,但没有任何效果。我想将文本放在图像框的正中央,但它要么出现在图像框下方,要么出现在向下推整个图像框的位置。绝对位置是我在我的代码中几乎不使用的东西,因为我的老师对它很重要,但我没有找到任何其他方法来解决这个问题?

HTML

<div class="class">
<img src="http://lorempixel.com/400/200/sports/1/Dummy-Text" alt="abc jme">
  <div class="texto">
   <h2>goalkeepers</h2>
  </div>
</div>

CSS

.class{
   width:50%;
   height:21vw;
   float:left;
   overflow: hidden;
}
.class img{
   width:100%;
   height:120%;
   margin-top:-3.5vw;
   transition: ease-in-out 0.55s;
}

.class img:hover{
  -webkit-filter: blur(10px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
   filter: blur(5px);
   opacity: 1;
   transform:scale(1.05);
}
.texto h2{
   margin-top:0;
   margin-left:0;
   text-align: center;
   position: relative;
}
.texto{
   width:auto;
   height:auto;
   margin:auto;
   position: absolute;
}

乐 Fiddle: https://jsfiddle.net/32ed44cf/

这里的技巧是将 position: relative 添加到父元素,然后在父元素的中心添加 position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%)

将来,这里有一个关于如何居中的非常好的参考https://www.w3.org/Style/Examples/007/center.en.html

.class {
  width: 50%;
  height: 21vw;
  float: left;
  overflow: hidden;
  position: relative;
}

.class img {
  width: 100%;
  height: 120%;
  margin-top: -3.5vw;
  transition: ease-in-out 0.55s;
}

.class img:hover {
  -webkit-filter: blur(10px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  opacity: 1;
  transform: scale(1.05);
}

.texto h2 {
  margin-top: 0;
  margin-left: 0;
  text-align: center;
  position: relative;
}

.texto {
  width: auto;
  height: auto;
  margin: auto;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="class">
  <img src="http://lorempixel.com/400/200/sports/1/Dummy-Text" alt="abc jme">
  <div class="texto">
    <h2>goalkeepers</h2>
  </div>
</div>

试试这个

* {
  box-sizing: border-box;
  font-family: sans-serif;
}

.container {
   position: relative;
   overflow: hidden;
}

img {
   width: 100%;
   opacity: .8;
} 

.centered-text {
   border-radius: 6px;
   padding: 0 6px;
   color: white;
   text-align: center;
   background-color: rgba(0, 0, 0, .4);
   position: absolute;
   top: 50%;
   left: 50%;
   -webkit-transform: translate(-50%, -50%);
   -moz-transform: translate(-50%, -50%);
   -o-transform: translate(-50%, -50%);
   -ms-transform: translate(-50%, -50%);
   transform: translate(-50%, -50%);
}
<div class="container">
  <img src="https://parrot-tutorial.com/images/nature_autumn.jpg">
  <div class="centered-text">
    <h4>Centered</h4>
    <p>Lorem ipsum dolor sit amet.</p>
  </div>
</div>

参考: How To Position Text Block Over an Image