【问题标题】:margin : auto not working vertically?边距:自动不能垂直工作?
【发布时间】:2013-07-17 03:38:38
【问题描述】:

我尝试在外部 div 中将 div 垂直居中,但它不起作用。我试图在网上四处寻找,但找不到我的具体问题的解释...... 当尝试水平对齐时,它正在工作 => "margin:0 auto;"

有人吗?

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

【问题讨论】:

    标签: css margin


    【解决方案1】:

    margin:auto 可以以已知高度垂直居中only absolutely positioned elements (fiddle):

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

    【讨论】:

      【解决方案2】:

      你可以使用这个插件做你的工作:

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

      然后你可以像这样使用它:

      $("#mydiv").verticalAlign()
      

      对于您的代码:

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

      只需添加以下内容:

      $("#mydiv").verticalAlign()
      

      【讨论】:

        【解决方案3】:

        使用display:table;

        标记

        <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

        【讨论】:

        • 容器的 display: table-cell 足以使内容居中。仅当需要容器本身的边距时,才需要带有display: table 的包装器。
        【解决方案4】:

        试试这个代码。它的工作......

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-04-15
          • 1970-01-01
          • 2017-03-25
          • 2018-03-16
          • 1970-01-01
          • 2018-06-20
          • 2013-01-02
          相关资源
          最近更新 更多