【问题标题】:Align vertical and horizontal a fixed div with relative sizes垂直和水平对齐具有相对大小的固定 div
【发布时间】:2012-09-22 05:54:51
【问题描述】:

我问这个问题是因为它在 chrome 浏览器上正确显示,但在 Firefox/IE 中却没有。

我想要一个 div,它必须根据窗口垂直和水平对齐。它也有相对大小。你能帮我么 ?我试过了,但它只适用于 Chrome:

    #itemNewsFS {
       position:fixed;
       display:none;
       width: 50%;
       left: 50%; 
       margin-left: -25%;
       height: 80%;
       top: 50%;
       margin-top: -40%;
    }

谢谢!

【问题讨论】:

    标签: internet-explorer firefox css alignment


    【解决方案1】:

    边距(垂直和水平)是相对于包含框的宽度计算的,请阅读 CSS2.1 规范的摘录:little link

    要实现您想要的,您可以保留您的 margin-left 值,但您必须使用 JavaScript 来修复 margin-top

    document.getElementById("itemNewsFS").style.marginTop = Math.floor(window.innerHeight * 40 / 100) + "px";
    

    【讨论】:

    • 我想我们也可以使用overflow:auto;float 代替javascript?如果我错了,请纠正我。
    • 我知道如何用 JavaScript 来做,我试图找到一个 CSS 代码来做
    • @themazz 你不能。你读过 CSS 规范摘录吗?如果您想将 position: fixed; 元素与相对 height 垂直居中,那么这是唯一的方法。
    • @Mr_Green 你能解释更多吗?
    • @Abody97 我可以为您提供link,这可能与此问题相同。
    【解决方案2】:

    试着去做:

    <div class="block">
       <div id="itemNewsFS">
           Unknown stuff to be centered.
       </div>
    </div>
    
    .block {
        text-align: center;
        background: #c0c0c0;
        border: #a0a0a0 solid 1px;
        margin: 20px;
        height: 100%; /* Put your height here */
    }
    
    .block:before {
        content: '';
        display: inline-block;
        height: 100%; 
        vertical-align: middle;
        margin-right: -0.25em; /* Adjusts for spacing */
    
    }
    
    #itemNewsFS {
    display: inline-block;
        vertical-align: middle;
        width: 300px;
        padding: 10px 15px;
        border: #a0a0a0 solid 1px;
        background: #f5f5f5;
    }​
    

    来源:http://css-tricks.com/centering-in-the-unknown/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-25
      • 2011-04-26
      • 1970-01-01
      • 2017-07-01
      • 2020-10-21
      • 1970-01-01
      • 2012-10-10
      相关资源
      最近更新 更多