Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 233
hannah Avatar asked Dec 19 '22 13:12

hannah


2 Answers

Try setting the top to a percentage:

.text {
    position: absolute;
    top: 25%;
    left: 0;
    color: white;
    text-align: center;
    bottom: 0;
    right: 0;
}
like image 195
Jim Avatar answered May 05 '23 09:05

Jim


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/

like image 23
Hardy Avatar answered May 05 '23 07:05

Hardy