【问题标题】:Using Fixed Positioning on a Vertically Aligned Div在垂直对齐的 Div 上使用固定定位
【发布时间】:2014-07-11 00:40:47
【问题描述】:

希望有一个简单的解决方案。基本上我想要做的是在浏览器的垂直中心放置一个 div (#hello) 使用固定定位,这样它就不会在滚动时移动。到目前为止,这是我的 HTML:

<section id="home">
    <div id="home-container">
        <div id="hello"></div>
    </div>
</section>

还有 CSS:

#home {
    display: table;
    overflow: hidden;
    margin: 0px auto;
}

*:first-child+html #home {
    position: relative;
}

* html #home {
    position: relative;
}

#home-container {
    display: table-cell;
    vertical-align: middle;
}

*:first-child+html #home-container {
    position: absolute;
    top: 50%;
}

* html #home-container {
    position: absolute;top:50%;
}

*:first-child+html #hello {
    position: relative;
    top: -50%;
}

* html #hello {
    position: relative;
    top: -50%;
}

#home {
    height: 100%;
}

现在 div 在“home”部分垂直居中,但在滚动时移动。我尝试将#home 和#home-container 更改为固定定位,但它不起作用。

我已经搜索了很多,如果已经存在类似的线程,我深表歉意。希望有人能指出我正确的方向。提前致谢!

【问题讨论】:

  • * 对于所有内容?例如* html?你不知道它是做什么的,所以先了解一下……
  • 是的,这是教程中使用的代码。我会尝试删除它们,看看是否有帮助。
  • 现在不要再参考那个教程了...你能提供链接吗
  • 太疯狂了..不要提到那个

标签: html css css-position vertical-alignment


【解决方案1】:

将 div 垂直对齐到具有固定位置的垂直中心的概念是添加 position:fixed 属性(指定偏移量),然后在 div 高度一半的顶部放置一个负边距。例如,假设 #hello 的高度为 100px:

    #hello {
      position:fixed;
      top:50%;
      margin-top:-50px;
    }

位置:固定; div 将相对于您的文档窗口。

【讨论】:

    【解决方案2】:

    您可以添加此样式。此外,您必须在中间添加一些内容,以便您可以正确检查,或者给父 div 一些高度(以 px 为单位)。没有高度的空父 div 不会反映更改。

    #hello{
        position: fixed;
        top: 50%;
    }
    

    你可以看看这个小提琴:

    http://jsfiddle.net/76a4j/6/

    【讨论】:

      【解决方案3】:

      用这个替换你的css

      *{margin:0; padding:0;}
      html, body{height:100%;}
      #home{display:table; margin:auto; height:100%; width:100%; position:fixed; top:0px; left:0px;}
      #home-container{display:table-cell; vertical-align:middle; text-align:center;}
      #hello{display:inline-block;}
      

      我为你做了一个小提琴。看看http://jsfiddle.net/fQwFL/

      希望它能解决您的问题。

      【讨论】:

        猜你喜欢
        • 2019-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-12
        • 2015-05-26
        • 2022-01-15
        相关资源
        最近更新 更多