【问题标题】:Vertical centering of div without Javascript when div's height isn't fixed当 div 的高度不固定时,没有 Javascript 的 div 垂直居中
【发布时间】:2015-04-11 02:25:01
【问题描述】:

高度不固定时,我想在不使用 JavaScript 的情况下将 div 垂直居中。

我发现here 一个想法。

我想知道这个问题是否有其他解决方案。

【问题讨论】:

    标签: html css vertical-alignment


    【解决方案1】:

    这行得通:

    这里是链接:http://jsbin.com/uvodop/2/edit

    查看它在框中的垂直对齐方式。高度也不是固定的。

    希望它能回答你的问题。

    <html>
    <head>
        <title>HTML Div vertical align using CSS</title>
        <style type="text/css">
            .outerDiv {
                border: solid 1px #000000;
                width: 300px;
                padding: 5px 2px 5px 2px;
            }
    
            .innerDiv {
                width: 95%;
                margin: 0px auto;
                padding: 40px 0px 40px 5px;
                border: solid 1px #000000;
            }
        </style>
    </head>
    <body>
        <div class="outerDiv">
            <div class="innerDiv">
                This text is placed inside the next HTML div tag.<br />
                CSS style is used to vertical align the nested div and text.
            </div>
        </div>
    </body>
    </html>
    

    【讨论】:

    • 如果outerDiv的高度是固定的,比如700px,它就不起作用了。
    • 好吧,我修好了...如果您希望它动态更改,我想您可能需要 JavaScript...jsbin.com/uvodop/2/edit
    【解决方案2】:

    虽然这是一个旧线程,但我认为这个答案可能会对某人有所帮助。如果 IE 的版本灵活到至少 IE > 8,那么您可以使用display:table-cell 并使用默认的vertical-align 功能。

    在下面的代码中,div.hover 是要垂直居中对齐的 div 没有分配任何高度,但是父级分配了 100% 的高度以填充屏幕。

    看看这个

    .outer {
      position: fixed;
      top: 0px;
      left: 0px;
      width: 100%;
      height: 100%;
      background-color: #aaa;
      display: table;
    }
    .inner {
      display: table-row;
      border: 1px solid #0f0;
      height: 100%;
    }
    .center {
      display: table-cell;
      border: 1px solid #00f;
      vertical-align: middle;
      height: 100%;
    }
    .hover {
      width:100px;
      border: 1px solid #f00;
      margin-left: auto;
      margin-right: auto;
    }
    <div class="outer">
      <div class="inner">
        <div class="center">
          <div class="hover">
            I am a random text to give the div some height
          </div>
        </div>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 2019-06-20
      • 2018-07-05
      • 2013-06-24
      • 2013-06-15
      • 2015-08-05
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多