Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I try to vertically center a div in an outer div but it doesn't work. I tried to look around on the web but couldn't find an explanation for my specific problem... When trying to align horizontally it's working => "margin:0 auto;"

Anyone ?

<div style="height:240px;width:100%;">

 <div style="width:33%;height:100px;margin:auto 0;">
   <span class="" style="font-size:26px">Hello </span>
   <br/><br/>
   <img style="width:150px" src="example.jpeg"
/>
 </div>

</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use this plugin do your work:

jQuery.fn.verticalAlign = function ()
{
    return this
            .css("margin-top",($(this).parent().height() - $(this).height())/2 + 'px' )
};

Then you can use it like:

$("#mydiv").verticalAlign()

For your code:

<div style="height:240px;width:100%;">

 <div id="mydiv" style="width:33%;height:100px">
   <span class="" style="font-size:26px">Hello </span>
   <br/><br/>
   <img style="width:150px" src="example.jpeg"
/>
 </div>

</div>

Just add the following:

$("#mydiv").verticalAlign()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...