Bootstrap在图片内居中显示文字

时间:2021-10-21 17:47:00

图片的父容器position设置为relative。文字position设置为absolute。

.thumbnail {
  position: relative;
}

.caption {
  position: absolute;
 top: 45%;
 left: 0;
  width: 100%;
}

示例:

<!DOCTYPE html>
<html lang="zh">
<head>
 <title>Bootstrap图片内显示文字</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
 
<style type="text/css">
  .thumbnail {
    position: relative;
    }

    .caption {
    position: absolute;
    top: 45%;
    left: 0;
    width: 100%;
    }
 </style>
</head>
<body>
  <div class="row" id="box-search">
  <div class="thumbnail text-center">
    <img src="img/hello_world.png" alt="" class="img-responsive">
    <div class="caption">
      <p>世界很大,我想去看看</p>
    </div>
  </div>
</div>
</body>
</html>