Unknown User
Unknown User

Reputation: 525

How to center text vertically and horizontally over an image

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;
  }

Upvotes: 1

Views: 4579

Answers (4)

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

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>

Upvotes: 9

UncaughtTypeError
UncaughtTypeError

Reputation: 8732

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>

Upvotes: 0

QuidamAzerty
QuidamAzerty

Reputation: 368

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.

Upvotes: 1

Tirthraj Barot
Tirthraj Barot

Reputation: 2679

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>

Upvotes: 0

Related Questions