hannah
hannah

Reputation: 140

position: absolute bottom: 0 not working when centering text on image

I'm trying to place text in the middle of an image on a page. I'd like to use this on other images on the page with different heights and widths as well. I have the image relatively positioned and the text absolutely positioned, but bottom: 0 doesn't seem to be working:

<div class="image">
<img src="http://lorempixel.com/300/300/">
    <header class="text">
        <h1>header</h1>
        <a href="#">button</a>
    </header>
</div>

Here's the CSS:

.image {
  display: inline-block;
  position: relative;
}

.text {
  position: absolute;
  top: 0;
  left: 0;
  color: white;
  text-align: center;
  bottom: 0;
  right: 0;
}

.text h1 {
  text-transform: uppercase;
  font-family: Helvetica, Arial;
  font-size: 16px;
  letter-spacing: .5px;
}

.text a {
  font-size: 14px;
  border: 1px solid white;
  padding: 5px 30px;
  color: white;
  text-decoration: none;
}

And a link to the fiddle: http://jsfiddle.net/yg4Ar/

Upvotes: 5

Views: 9663

Answers (3)

Hardy
Hardy

Reputation: 5631

You have :

position: absolute;
top: 0; // This keeps text top.
left: 0;
color: white;
text-align: center;
bottom: 0;
right: 0;

So this makes your text to 100% height.. because of that top:0.. so just remove that top:0.

And if you want to center your text vertically, you have to specify/calculate some height for your text and add half of it as minus margin to your CSS and put top value to 50% like:

.text {
    position: absolute;
    top: 50%;
    left: 0;
    margin-top: -30px; // This should be half of your text div:s height
    color: white;
    text-align: center;
    bottom: 0;
    right: 0;
} 

Example: http://jsfiddle.net/9zyx2/

Upvotes: 5

freeWind
freeWind

Reputation: 148

Try this:

.text {
    position:absolute;
    top: 100px;
    left: 0;
    color: white;
    text-align: center;
    bottom: 0;
    right: 0;
}

Upvotes: 1

Jim
Jim

Reputation: 586

Try setting the top to a percentage:

.text {
    position: absolute;
    top: 25%;
    left: 0;
    color: white;
    text-align: center;
    bottom: 0;
    right: 0;
}

Upvotes: 5

Related Questions