html - 如何在已经居中的图像上叠加文本中心底部?

标签 html css

我在边距、位置等方面玩了很多,但如果不粗略地手动输入位置,我就无法将文本居中放置在我想要的位置,即 left: 10px; 。这可能很简单,但我作为一个学习者无法理解

.container {
  position: relative;
}

.text-block-main {
  position: absolute;
  bottom: 5%;
  right: 44%;
  background-color: black;
  opacity: 75%;
  color: white;
  padding-left: 20px;
  padding-right: 20px;
  border-radius: 15px;
  border: 2px solid white;
  padding: 10px;
}
<div class="container">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1200px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg" alt="vvg" style="height:100%;" class="center">
  <div class="text-block-main">
    <h2> The Starry Night </h2>
    <h3> Vincent van Gogh </h3>
  </div>
</div> 

它有点居中(手动),但不是真的居中,取决于我使用的图像本身,所以我必须为我想使用的每个图像调整它。感谢对此的一些帮助

最佳答案

使用 flex 的解决方案。在container类上指定display: inline-flex,采用img标签图片的形式。

同时从 text-block-main 类中删除 bottomright

我在 css 中标记了所有的编辑。

.container {
  position: relative;
  
  display: inline-flex; /*add this it*/
  align-items: center; /*add this it*/
  justify-content: center; /*add this it*/
}

.text-block-main {
  position: absolute;
  /*bottom: 5%;*/ /*remove this it*/
  /*right: 44%;*/ /*remove this it*/
  background-color: black;
  opacity: 75%;
  color: white;
  padding-left: 20px;
  padding-right: 20px;
  border-radius: 15px;
  border: 2px solid white;
  padding: 10px;
}
<div class="container">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1200px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg" alt="vvg" style="height:100%;" class="center">
  <div class="text-block-main">
    <h2> The Starry Night </h2>
    <h3> Vincent van Gogh </h3>
  </div>
</div>

关于html - 如何在已经居中的图像上叠加文本中心底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64909579/

相关文章:

html - 仅使用 CSS 输入占位符

asp.net - AddThis 标记不会显示在 TinyMCE html 编辑器中

css - 为什么 <table> 不适合布局而 <div> 适合?对于屏幕阅读器用户

javascript - 在调整窗口大小时右对齐

html - css布局网格容器中心

html - ul li标签位置

html - 字体大小问题

html - 为什么在清除 :both is mentioned? 时 float 命令起作用

javascript - 旋转图像

css - 使用 CSS 自动调整 DIV 宽度?