user1694077
user1694077

Reputation:

Vertically center a header on top of an image

I'm trying to vertically center an h2 on top of an img, but I can't get it exactly centered. I'm almost there, but how do I get it exactly there?

Details:

HTML

<div class="image">
    <img src="http://bit.ly/gUKbAE" />
    <div class="wrapper">
        <h2>Title</h2>   
    </div>
</div>

CSS

.image { 
    position: relative; 
}

.wrapper {
    position: absolute;
    top: 50%; 
    left: 0;
}

h2 {
    margin: 0;
    padding: 0;
}

I've put it here: http://jsfiddle.net/kmjRu/15/

Upvotes: 0

Views: 127

Answers (2)

pinmouse
pinmouse

Reputation: 33

Also, if you set the font size of your h2, then you can just add a negative top-margin to your wrapper (or h2 I believe), like so...

.image { 
    position: relative; 
}

.wrapper {
    position: absolute;
    top: 50%; 
    left: 0;
    margin-top: -15px; /* Set negative margin here to pull it up */
}

h2 {
    margin: 0;
    padding: 0;
    z-index: 2;
    font-size: 30; /* Set font size here */
}

I made your h2 font-size 30 and then just set the .wrapper margin-top to -15 here.

Here it is on jfiddle http://jsfiddle.net/kmjRu/15/

Upvotes: 0

Alex W
Alex W

Reputation: 38253

The reason it is not perfectly centered is because it is making the top of the line of text at 50%.

Simple fix is changing the line-height to be 0px:

.wrapper
{
   position: absolute;
   top: 50%;
   line-height: 0px;
   left: 0;
}

Upvotes: 1

Related Questions