简体   繁体   中英

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:

  • I don't know the height of any of the elements, so I can't use fixed heights and setting the image as a background is not an option because the image is part of the content
  • Some have suggested display:table , but I've tried it and it doesn't play nice with position:relative and position:absolute

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/

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM