如何在HTML中的图像上居中文本?

时间:2016-10-30 01:52:59

标签: html css html5 css3

我一直试图将文字放在图像上,然而,它不会居中。我已经在Stack Overflow上查看了各种问题,但没有一个可行。

footer {
  align-content: center;
  justify-content: center;
}

.jumbotron {
  display: flex;
  align-items: center;
  background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Wave_Panorama.jpg/1024px-Wave_Panorama.jpg');
  background-size: cover;
  color: #ffffff;
  height: 500px;
  text-shadow: 0.25px 0.25px 0.25px #000000;
}

.jumbotron h2 { 
  font-size: 60px;
  font-weight: 700;
  margin: 0;
  color: #fff;
  text-align: center;
  position: absolute; 
  text-align: center;   
  margin: 0;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<footer>
  <section class="jumbotron">
    <div class="container">
      <div class="row text-center">
        <h2>By Me</h2>
      </div>
    </div>
  </section>
</footer>

我对HTML很陌生,所以如果我的代码混乱/混乱/完全错误,那可能就是原因。我也试图使用Stack Overflow中的代码片段修复它,所以如果不需要某些部分,请告诉我,以便我可以解决它。

2 个答案:

答案 0 :(得分:1)

或者,你知道,只需稍微清理一下代码...... *删除了超级<div>容器,将flex: 1 1 0;放在应有的位置,并删除了其他一些非感性的CSS。

.jumbotron {
display: flex;
text-align: center;
background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Wave_Panorama.jpg/1024px-Wave_Panorama.jpg');
background-size: cover;
color: #ffffff;
height: 500px;
text-shadow: 0.25px 0.25px 0.25px #000000;
}
.text-center {
  flex: 1 1 0;
  margin: auto;
}
.jumbotron h2 { 
font-size: 60px;
font-weight: 700;
text-align: center;   
}
<footer> 
<section class="jumbotron">
<div class= "row text-center">
<h2>By Me</h2> 
</div>
</section>
</footer>

答案 1 :(得分:0)

定位relative而不是absolute

footer {
align-content: center;
justify-content: center;
}

.jumbotron {
display: flex;
align-items: center;
background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Wave_Panorama.jpg/1024px-Wave_Panorama.jpg');
background-size: cover;
color: #ffffff;
height: 500px;
text-shadow: 0.25px 0.25px 0.25px #000000;
  
}

.jumbotron h2 { 
font-size: 60px;
font-weight: 700;
margin: 0;
color: #fff;
text-align: center;
position: relative; /* MODIFICATION */
text-align: center;   
margin: 0;
 
}
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<footer> 
<section class="jumbotron">
<div class= "container">
<div class= "row text-center">
<h2> By Me</h2> 
</div> 
</div>
</section>
</footer>