简体   繁体   中英

Centering text in Dynamic Image

I have an image that is dynamic: 100% width and 100% height, how do I keep the text inside in the center vertically and horizontally no matter what size it is?

https://jsfiddle.net/jzhang172/h9y8umr2/

 html, body{ margin:0px; } .wrapper{ position:relative; } img{ height:100%; width:100%; position:relative; } .text-wrapper{ position:absolute; top:50%; left:50%; margin-left:-25%; margin-top:-25%; } 
 <div class="wrapper"> <img src="http://www.wildlifetrusts.org/sites/default/files/images/Planting%20along%20realigned%20River%20Chelt%20Gloucs%20WT,%20EA%20and%20landowner2%20comp.jpg"> <div class="text-wrapper"> <h2>Sample Text</h2> <p>Text Sample</p> </div> </div> 

I removed margin-left: -25% and margin-top: -25% and added margin: 0 auto; and that fixed it

    .text-wrapper{
  position:absolute;
  top:50%;
  left:50%;
  margin: 0 auto;
  }

Updated fiddle:

I think you need to use transform: translate() to center the text. By the way, it's better to use CSS Flexboxes - fiddle here :)

 html, body{ margin:0px; } .wrapper{ position:relative; } img{ height:100%; width:100%; position:relative; } .text-wrapper{ position:absolute; top:50%; left:50%; transform: translateX(-50%) translateY(-50%); } 
 <div class="wrapper"> <img src="http://www.wildlifetrusts.org/sites/default/files/images/Planting%20along%20realigned%20River%20Chelt%20Gloucs%20WT,%20EA%20and%20landowner2%20comp.jpg"> <div class="text-wrapper"> <h2>Sample Text</h2> <p>Text Sample</p> </div> </div> 

I think your only problem is your text-wrapper class.

If you write top:50% and left:50%, the top-left corner of your text div will be the exact center of your img.

You just have to adjust your margin-left and margin-top to the size of your text then (write width/2 and height/2 of your text for the margins) :)

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