html - Text vertically and horizontally centered over a responsive image -
i'm looking center text both vertically , horizontally on image grows when page gets wider.
i had image set background div of fixed height, in case relatively easy center it, because background images aren't structural, couldn't set height automatic function of width, , had toss option out when went more responsive design.
so i've got div 2 elements in it, img , overlay text. image width set 100% of width of container, , height varies accordingly. consequence, though, can't set overlay text postion:absolute , top:80px or something, because distance top have vary. , doing top:25% or whatever doesn't work, because a) if page width shrinks squeeze text, or if there's more text, vertical centering thrown off when there more/less lines, , b) percentage arbitrary -- it's not 50 or something, because put top of text overlay 50% down image, when want center of overlay there.
i've looked, among other things, @ this post, close -- in both solutions, image height incapable of resizing, , in former, js loads @ page load, freezes, if change page width/height, things out of whack. ideally, solution wouldn't involve js reason (even if reloaded on every resize, feels non-ideal), if that's solution, i'll take it.
also, added details/fun, i've set max-height on image, because don't want exceed 300px height, on cinema display.
basic fiddle of current attempt here, , identical code below. ideas? thanks!
html
<div class='quotation_div'> <img src='http://www.mountainprofessor.com/images/mount-ranier-mount-features-2.jpg'> <div class='overlay'> <p>any reasonable amount of text should able go here. want able center vertically if takes 2 or 3 lines.</p> </div> </div>
css
.quotation_div { position: relative; display: table; } img { width: 100%; max-height: 300px; } .overlay { z-index: 99; width: 70%; margin-left: 15%; vertical-align: middle; position: absolute; top: 25%; /* obvious problem, cause it's arbitrary */ } p { text-align: center; color: red; font-size: 165%; font-weight: lighter; line-height: 2; }
you can use css background-size
set width 100% , height calculated maintain aspect ratio.
here's a fiddle using technique.
if want image html element suggest set it's position absolute , use same method of disply:table-cell
center overlay:
here's a fiddle using method, 1 stretches image because of max-height
.
Comments
Post a Comment