1

All I want to do is center my text vertically and horizontally on an img..

Tried a lot of things but nothing works so far :/

    <div class="img_container">
     <img class="cover-image" src="img.jpg" alt="omg" />
     <h2> bla bla bla </h2>
   </div>

  .img_container {
    width: 100%;
  }

  .img_container h2 {
    margin: 0;
  }
isherwood
  • 58,414
  • 16
  • 114
  • 157
Unknown User
  • 505
  • 1
  • 7
  • 19
  • Check this other [question](http://stackoverflow.com/questions/19461521/how-to-center-an-element-horizontally-and-vertically) might be what you are looking for – T04435 Jun 09 '16 at 11:11

4 Answers4

9

Just use position absolute and translate. Will be perfect centered (horizontally and vertically)

.img_container {
  position: relative;
}
.img_container img {
  width: 100%;
  height: auto;
}
.img_container h2 {
  color: white;
  text-shadow: 1px 1px 1px black;
  position: absolute;
  top: 50%;
  left:  50%;
  -webkit-transform: translate(-50%, -50%); /* iOS */
  transform: translate(-50%, -50%);
}
<div class="img_container">
  <img class="cover-image" src="http://lorempixel.com/400/200/sports/" alt="omg" />
  <h2> bla bla bla </h2>
</div>
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
1

Here's a good tuto to do it: css-tricks.com - Text Blocks Over Image.

Basically, you can fix your text with position: absolute then move it where you want to with top, left, etc.

QuidamAzerty
  • 356
  • 4
  • 10
  • 3
    Please see Marcos Pérez Gude's answer - In my opinion, Marcos's answer enhances this solution, is better and is more suited to what tools we have at our disposal these days rather than when that article came out 7 years ago ... – David Wilkinson Jun 09 '16 at 09:09
0

1) You could simply put the image in the background of the image-container and simply give the css properties to image container as

style="vertical-align:middle and text-align center"

Or

2) You can use these classes and get your work done.

.image {
    position:relative;
}

.text {
    left: 0;
    position:absolute;
    text-align:center;
    top: 30px;
    width: 100%
}

where html code would be like

<div class="image">
    <img src="sample.png"/>
    <div class="text">
       Text of variable length
    </div>
</div>
Tirthraj Barot
  • 2,671
  • 2
  • 17
  • 33
0

Yet another manner of implementing this:

.img_container {
    width: auto;
    position: relative;
    display: inline-block;
  }

.img_container h2 {
    position: absolute;
    top: 40%; /* adjust accordingly to suit requirements */
    left: 0;
    right: 0;
    text-align: center;
    background: rgba(0, 0, 0, 0.5);
    color: white;
    padding: 10px;
    box-sizing: border-box;
    margin: 0;
}
<div class="img_container">
     <img class="cover-image" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97250&w=350&h=250" alt="omg" />
     <h2>Postioned Absolute</h2>
   </div>
UncaughtTypeError
  • 8,226
  • 4
  • 23
  • 38