将文字放在图像上

时间:2017-05-24 22:11:18

标签: html css image text box

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

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;
}

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

2 个答案:

答案 0 :(得分:2)

这里的技巧是将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>

答案 1 :(得分:0)

尝试一下

* {
  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