1

I am trying to center center text overlaying an image. Here's what my code is:

<div class="col-md-6">
    <div class="safaripreview">
        <img src="img/safari1.png" class="img-responsive" alt="">
        <h3>Our String Of Pearls</h3>
    </div>
</div>

and my CSS is currently

.safaripreview
{
  position: relative; 
}

.safaripreview h3
{
  position: absolute; 
  bottom: 0;
  width: 100%;
  color: white; 
  padding: 10px;
  font-family: 'Montserrat', sans-serif;
  font-weight: 700;
}

This is producing:

enter image description here

when i want to achieve this

enter image description here

Is there a better way to achieve this? Flexbox?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Paolo Resteghini
  • 382
  • 1
  • 3
  • 14

3 Answers3

1

Yes. flexbox

.safaripreview {
  display: inline-block;
  position: relative;
}
.safaripreview {
  display: inline-block;
}
.safaripreview h3 {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}
<div class="safaripreview">
  <img src="http://www.fillmurray.com/460/300" class="img-responsive" alt="">
  <h3>Our String Of Pearls</h3>
</div>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161
0
position: absolute;
top: 50%;
right: 30px;
left: 30px;

transform: translateY(-50%);

Will achieve this for you.

You could also do:

position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;

align-items: center;
justify-content: center;

display: flex;

But this has less support and obviously more lines :)

Dan Gamble
  • 3,965
  • 1
  • 24
  • 44
0

change css this way

.safaripreview h3
{
  position: absolute; 
  top: 50%;
  left:50%;
  transform: translate(-50%, -50%);
  width: 100%;
  color: white; 
  padding: 10px;
  font-family: 'Montserrat', sans-serif;
  font-weight: 700;
}
Lalji Tadhani
  • 14,041
  • 3
  • 23
  • 40