简体   繁体   中英

Absolute position text over image using CSS3 not working on Safari

I am trying to center a element with text over an image and my code works fine everywhere, except on Safari (for windows, if that means anything), it even works on Internet Explorer 9!

Here is a fiddle: http://jsfiddle.net/keleturner/b7DeH/

The only way I have found is to give the .main a set height, but I can't do this for various reasons. Is there a way to get it the text to overlay in the middle of the image with a height: auto;?

I'm not sure if you have a specific reason for the heavy div nesting, but I've cleaned it up here: http://jsfiddle.net/b7DeH/3/

HTML:

<div class="main">
    <span>Text</span>
    <img src="http://placekitten.com/300/200?image=3" />
</div>

CSS:

span  {
    position: absolute;
    width: 100%; top: 50%; 
    /* and other prefixes */
    transform: translateY(-50%); 
    font-size: 20px; font-weight: 700; 
    color: red; text-align: center; }

The problem, as you noticed, seems to stem from a height issue. You have height: 100% for .in and .out but without any parent/ancestors to tell it what that height is 100% of, it'll just keep going, and I imagine it's basically taking the 100% height of the document, hence why it centers to the page and not the divs.

Try using absolute positioning for your span too.

span {
   position: absolute;
}

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