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

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

css - margin : auto not working vertically?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...