【问题标题】:How to put a div in the middle of the page [duplicate]如何在页面中间放置一个 div [重复]
【发布时间】:2013-11-29 00:32:47
【问题描述】:

不在页面中间,如 margin: 0 auto; 我说的是从上到下的中心。 提前谢谢!

【问题讨论】:

  • 你说垂直对齐,搜索一下
  • 我一直告诉人们在发布新问题之前请在这里搜索。给你stackoverflow.com/questions/16439769/…
  • 这已被问了 100 次。你谷歌了吗?
  • html5 提供了一些更好的解决方案,所以我不认为它太糟糕以至于被再次询问

标签: css html


【解决方案1】:

在 html5 中,使用 flexbox 非常简单:

这篇文章描述了如何做到这一点 http://coding.smashingmagazine.com/2013/05/22/centering-elements-with-flexbox/

这里是演示(也来自文章) http://jsfiddle.net/pnNqd/

HTML:

<h1>OMG, I’m centered</h1>

CSS:

html {
    height: 100%;  
} 

body {
    display: -webkit-box;   /* OLD: Safari,  iOS, Android browser,
                                    older WebKit browsers.  */
    display: -moz-box;      /* OLD: Firefox (buggy) */ 
    display: -ms-flexbox;   /* MID: IE 10 */
    display: -webkit-flex;  /* NEW, Chrome 21+ */
    display: flex;      /* NEW: Opera 12.1, Firefox 22+ */

    -webkit-box-align: center; -moz-box-align: center; /* OLD… */
    -ms-flex-align: center; /* you know the drill now… */
    -webkit-align-items: center;
    align-items: center;

    -webkit-box-pack: center; -moz-box-pack: center; 
    -ms-flex-pack: center; 
    -webkit-justify-content: center;
    justify-content: center;

    margin: 0;
    height: 100%;
    width: 100%; /* needed for Firefox */
} 

h1 {
    display: -webkit-box; display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -webkit-box-align: center; -moz-box-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;

    height: 10rem;
}

【讨论】:

    【解决方案2】:

    有多种方式:

    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: <50% of width from element>;
    margin-top: <50% of height from element>;
    

    或:

    HTML

    <div id="content-wrapper">
        <div class="wrapper">
            Some text  
        </div>
    </div>
    

    CSS

    #content-wrapper {
       display: table;
       width: 100%;
       height: 100%;
       text-align: center;
    }
    .wrapper {
       display: table-cell;
       vertical-align: middle;
       position: relative;
    }
    

    注意:这不会每次都有效.. 我自己做了这个site

    【讨论】:

      【解决方案3】:

      如果您的 div 绝对定位,这是最简单的方法。条件。您的 div 必须具有固定的宽度和高度

      #myBox{width:50px; height: 50px; position: absolute; margin: auto; top: 0; left: 0; bottom: 0; right: 0; border:solid 1px #000;} 
      

      http://jsfiddle.net/zM2J2/

      添加边框以显示轮廓。

      【讨论】:

        猜你喜欢
        • 2018-08-07
        • 1970-01-01
        • 2020-06-03
        • 2021-01-08
        • 2018-05-09
        • 2022-01-06
        • 2022-01-16
        • 2015-12-05
        • 2013-03-24
        相关资源
        最近更新 更多