【问题标题】:How can I align the text in the center of the image如何对齐图像中心的文本
【发布时间】:2020-01-10 16:33:04
【问题描述】:

我正在尝试将 div 中的文本居中,这个 div 包含一个图像 + 另一个 div,其中包含需要居中的文本。

见下图 https://ibb.co/XF7t0GG

我面临的问题是,也位于 div 中的图像不允许我在中心勾勒出文本。

我尝试应用填充和边距(甚至是负数)但是没有结果

所以现在这是我的 HTML 和 CSS 文件中的代码:

.destinations {
  padding: 5px 15px;
}

.destinations img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 10px;
}

.flex-item {
  width: 290px;
  height: auto;
  border-radius: 10px;
  margin: auto;
}

.flex-item-title {
  text-align: center;
  color: white;
  background-color: black;
  opacity: 0.8;
}
<div class="destinations">
  <div class="flex-item">
    <img src="assets/img/wassenaar.jpg">
    <div class="flex-item-title">Wassenaar</div>
  </div>
</div>

希望大家帮帮我

【问题讨论】:

    标签: html css


    【解决方案1】:

    这是一种将文本在图像上垂直和水平居中的方法:

    .destinations {
      padding: 5px 15px;
    }
    
    .destination {
      width: 290px;
      height: 290px;
      display: flex;
      border-radius: 10px;
      margin: auto;
      background-image: url("https://placekitten.com/500/500");
      justify-content: center;
      align-items: center;
    }
    
    .title {
      text-align: center;
      color: white;
      background-color: black;
      opacity: 0.8;
    }
    <div class="destinations">
      <div class="destination">
        <div class="title">Wassenaar</div>
      </div>
    </div>

    【讨论】:

    • 谢谢你的回答,这就是我想要的结果。有没有办法拥有 6 个不同的图像,因为它在所有其他目的地使用相同的背景?
    【解决方案2】:

    您可以使用以下 css 解决您的问题。

    .flex-item{
         width:300px;
         height:200px;
         position: relative;
            padding: 0;
            margin: 0;
            text-align: center;
        }
    
    
        .flex-item-title{
     position: absolute;
            top: 0; right: 0;
            bottom: 0; left: 0;
            width: 300px;
            height: 200px; 
            text-align: center;
                color: white;
                display: inline-table;
               vertical-align:middle;
               line-height:100%;            
            }
    

    尝试将您的 css 更改为这个 css,它会起作用。

    【讨论】:

    • 感谢您的建议,我在使用此解决方案时遇到的问题是图像后文本仍保留在 div 的底部
    • 请点赞并接受答案,以便日后人们能得到正确答案。谢谢你 。 @Brickinwall
    • 如果您对我的工作表示赞赏并且我的回答对您有用,您能否为答案投票? @Brickinwall 谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2016-10-13
    • 2017-12-10
    相关资源
    最近更新 更多