html - Dynamicly centre align elements with css -
is there way dynamically centre 2 objects using css ? dynamically centre mean if size of 1 of objects changes css wouldn't have change.
at moment achieve non dynamically im using css below, there way without knowing height dimensions of child element before hand , not being able set top:
, left:
correctly ?
html
<div class="box"> <img src="myimageurl" width="100" height="100"> </div>
css
.box { width: 200px; height: 200px; background: red; } .box img { margin-top: 50%; margin-left: 50%; position:relative; /* these values id dynamically set */ top: -50px; /* being half of image height */ left: -50px; /* being half of image width */ }
ive made js fiddle of issue here : http://jsfiddle.net/gnygxbxe/
you don't need calculate percentage position. use pseudo element centering it. need make sure element inside has properties display: inline-block
, vertical-align: middle
.
remember, elements inside box should in 1 line. if wanted put many of text, wrap text span
or inside .box
element.
for reference, read : https://css-tricks.com/centering-in-the-unknown/
see snippet. ie8+ supported.
.box { margin: 20px; background: #f8f8f8; border: #f0f0f0 solid 1px; text-align: center; white-space: nowrap; } .box:before { content: ''; display: inline-block; height: 100%; margin-right: -0.15em; vertical-align: middle; } .box > * { display: inline-block; padding: 15px; border: 1px solid #ccc; vertical-align: middle; }
<div class="box" style="height: 300px;"> <img src="http://placehold.it/100x100" /> </div>
Comments
Post a Comment