在容器内的背景图像上的文本

时间:2017-12-16 08:28:14

标签: html css image

我想要一个带有文本的响应式img。我尝试了几种不同的方式,当我尝试使其响应时,我会在一半的时候陷入困境,所以如果有人有一个简单的解决方案我很感激。

JSFiddle

代码段演示:



.img-fluid {
  max-width: 100%;
  height: auto;
  opacity: 0.4;
}

<div class="container">
  <img src="https://phillipbrande.files.wordpress.com/2013/10/random-pic-14.jpg?w=620" class="img-fluid">
  <div class="container">
    <h1>Header</h1>
  </div>
</div>
&#13;
&#13;
&#13;

5 个答案:

答案 0 :(得分:2)

  

你可以试试这个,这是代码

<html>
<head>
<style>
.container {
    position: relative;
    text-align: center;
    color: white;
}

.centered {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
</style>
</head>
<body>

<h2>Image Text within container</h2>

<div class="container">
  <img src="abc.jpg" alt="abc" style="width:100%;">
  <div class="centered">Centered</div>
</div>

</body>

答案 1 :(得分:1)

尝试将position设置为absolutefixed

.img-fluid{
    max-width:100%;
    height:auto;
    opacity:0.4;
    position: absolute;
}

答案 2 :(得分:1)

您可以使用font-size: calc(2vw + 2vh + 2vmin)(根据您的需要调整值),使文本对视口大小做出响应:)

.container {
  position: relative;
}

.container h1 {
  position: absolute;
  top: 0;
  left: 20px;
  font-size: calc(2vw + 2vh + 2vmin);
}

.img-fluid {
  max-width: 100%;
  height: auto;
  opacity: 0.4;
}
<div class="container">
  <img src="https://phillipbrande.files.wordpress.com/2013/10/random-pic-14.jpg?w=620" class="img-fluid">
  <h1>Header</h1>
</div>

答案 3 :(得分:0)

对于图像使用概念:

{
    display: table; 
    position: relative; 
    width: 100%; 
    height: auto;
}

要在图像上显示的文字使用概念

{
    display: table-cell;
    verticl-align: middle;
    position: absolute;
}

并调整图片上的文字给出顶部或底部或左侧或右侧} 使用类img-responsive不要在所有视图中更改图像的宽度和高度。

答案 4 :(得分:0)

HTML:

<div class="banner">
<img src="images/star.png" class="img-responsive" width="150" height="150" alt="star">
<h2>This is a Star</h2>
</div>

CSS:

.banner img{position:relative; width:100%; height:auto;}
 .banner h2{[psition:absolute; left:50%; top:50%; font-size:30px;
 line-height:30px;}