【问题标题】:How do I center text vertically and horizontally over image with percentage width and height?如何在具有百分比宽度和高度的图像上垂直和水平居中文本?
【发布时间】:2016-05-16 23:07:44
【问题描述】:

我一直在尝试将我的文本置于具有百分比宽度和高度的 div 上。我尝试使用 flexbox,但这对我来说并不奏效,所以我使用本教程作为参考:http://jsfiddle.net/4be9cp23/。 这是本教程的代码:

html

<div id="header">
        <h1>Home</h1>
</div>

CSS

#header {
        background-color: red;  
        color: white;
        text-align: center;
        vertical-align: middle;
        width: 100%; 
        height: 15%;
    }
#header h1{ display:inline-block; }

这是我正在处理的演示的链接http://codepen.io/maureenv/pen/dMEPap?editors=1100。我希望白色文本以龙的图像为中心(不移动它下面的表单容器类中的文本):

我按照上面的教程进行了尝试: HTML

 <div class="masthead-container">
      <img src="http://maureenvogel.com/images/charizard.jpg" class="masthead-img">

      <div class="quote-container">
        <div class="quote"> "This is my quote that won't center no matter what I do. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " </div>
        <div class="quote-author"> -quote by me</div>
      </div>
    </div> <!-- close masthead container div -->

CSS

.masthead-container .masthead-img{
  width: 100%;
  top: 0;
  left: 0;
  display: block;
  position: relative;
}

.masthead-container {
  text-align: center;
  vertical-align: middle;
}

.masthead-container .quote-container{
  display: inline-block;
}

.quote-container{
  top: 0;
  left: 0;
  color: white;
  position: absolute;
  text-align: center;
  width: 100%;
}

但是,文本拒绝居中并且 display-inline 块对我不起作用。请帮忙。谢谢!

【问题讨论】:

标签: html css css-position centering


【解决方案1】:

试试这样的:

.quote-container{
  top: 50%;
  left:  50%;
  color: white;
  position: absolute;
  text-align: center;
  display:inline-block;
  transform:translateX(-50%) translateY(-50%);
}

【讨论】:

    【解决方案2】:

    也许你可以尝试把你的img放在div的背景上,然后制作:

    .masthead-container{
        display: table;
        position: relative;
        width: 100%;
        height: 100%;
       background: url:(...);
    }
    
    .text-to-center{
        display: table-cell;
        text-align: center;
        vertical-align: middle;
      
    }
    <div class="masthead-container">
      <div class="text-to-center"><p>hello-world</p></div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 2018-02-28
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      相关资源
      最近更新 更多