margin : auto not working vertically?

杀马特。学长 韩版系。学妹 提交于 2019-12-11 11:15:47

问题


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>

回答1:


margin:auto can center vertically only absolutely positioned elements with known height (fiddle):

.container {
    position: relative;
}

.centered {
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
}



回答2:


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



回答3:


Use display:table;

Markup

<div class="outer">

 <div class="inner">
   <span class="" style="font-size:26px">Hello </span>
   <br /><br/>
   <img style="width:150px" src="http://placehold.it/150x50" />
 </div>

</div>

CSS

.outer
{
    display:table;
    height:240px;
    width:100%;
    border:1px solid black;
    text-align:center;
}
.inner
{
    display:table-cell;
    width:33%;
    height:100px;

    vertical-align:middle;
}

FIDDLE




回答4:


Try This Code. It's Working.....

<style>
.child {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 150px;
height: 150px;
border: 1px solid red;
margin: auto auto;
}

</style>
</head>
<body style="height: 100%; margin: 0;">
<div class="child"></div>
</body>


来源:https://stackoverflow.com/questions/17719198/margin-auto-not-working-vertically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!