【问题标题】:How do i center text on an image?如何在图像上居中文本?
【发布时间】:2017-10-10 08:05:18
【问题描述】:

我正在尝试将文本置于横幅图像的中心。

这是一个 jsfiddle。

https://jsfiddle.net/c6Lcr0ap/

HTML:

<div class="about-me">
  <div class="about-me__banner">

    <div class="about-me__banner-text">
      <h3>About Me</h3>
    </div>

    <div class="about-me__banner-image">
      <img src="https://i.imgur.com/qiUWxdd.png">
    </div>

  </div>
</div>

CSS:

h3 {
  color: orange;
}

【问题讨论】:

标签: html css


【解决方案1】:

.about-me__banner{
  position:relative;
  text-align:center;
}
.about-me__banner-text{
  position:absolute;
  width:100%;
  color: orange;
}
<div class="about-me">
    <div class="about-me__banner">
        <div class="about-me__banner-text">
            <h3>About Me</h3>
        </div>
        <div class="about-me__banner-image">
            <img src="https://i.imgur.com/qiUWxdd.png">
        </div>
    </div>
</div>

【讨论】:

    【解决方案2】:

    这其实很简单。

    首先,您需要将文本容器 .about-me__banner-text 相对于其父级 .about-me__banner 进行绝对定位,以便它可以停留在您的图像上。

    然后您可以使用 flexbox 将 .about-me__banner 内的所有内容垂直和水平居中,从而产生这些新规则:

    .about-me__banner {
      position: relative;
    
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .about-me__banner-text {
      position: absolute;
    }
    

    这应该可以解决问题。 You can check your modified fiddle here.

    【讨论】:

      【解决方案3】:

      .about-me {
        text-align:center;
      }

      【讨论】:

      • 请求是“在图像上”。
      • 他的问题是“在图像上居中文字”它没有说覆盖图像
      【解决方案4】:

      这里是https://jsfiddle.net/fkp9g1jr/

      .about-me__banner-text     
      

      类的宽度与图像相同

      【讨论】:

        【解决方案5】:

        如果固定高度适合您,这里有另一种解决方案:

        .about-me__banner-text {
            background-image: url("https://i.imgur.com/qiUWxdd.png");
            background-repeat: no-repeat;
            background-position: center;
            height: 57px;
            line-height: 57px;
            text-align: center;
        }
        

        这里是 jsfiddle:https://jsfiddle.net/01h8tqcc/

        更新:

        这样拆分样式可能会更好:

        .about-me__banner {
          background-image: url("https://i.imgur.com/qiUWxdd.png");
          background-repeat: no-repeat;
          background-position: center;
        }
        
        .about-me__banner-text {
          height: 57px;
          line-height: 57px;
          text-align: center;
        }
        

        jsfiddle: https:https://jsfiddle.net/01h8tqcc/1/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-07-01
          • 2017-04-11
          • 1970-01-01
          • 1970-01-01
          • 2016-04-16
          • 2011-11-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多