【问题标题】:Margin-top and Margin-bottom not working when I try to center vertically当我尝试垂直居中时,Margin-top 和 Margin-bottom 不起作用
【发布时间】:2016-05-14 04:50:46
【问题描述】:

试图将我的红色块放在网页中间,红色块底部的页脚块,最后是红色块顶部和页脚之间的白色块。 Margin-top 由于某种原因不起作用,尽管 left 和 right 是..

从本地文件复制了我的代码,因此有一些死链接,但我认为它们与 CodePen 无关,因为它仍然显示相同。

#container {
    display:block;
    position:relative;
    margin-left:auto;
    margin-right:auto;
    border:solid black;
    border-width: 3px;
    border-radius:5px;
    background-color:red;
    height:650px;
    width:850px;
    padding:1px;
}

#container.hover {
}

.wrapper {
    display:block;
    margin-left:auto;
    margin-right:auto;
    margin-top:auto;
    margin-bottom:auto;
    height:450px;
    width:650px;
    background-color:white;
    border:solid black;
    border-width:1px;
}

#grid {
    display:inline-block;
    float:left;
    background-color:white;
    height:10px;
    width:10px;
    border: solid black;
    border-width:.5px;
    margin-left:auto;
    margin-right:auto;
    margin-top: auto;
    margin-bottom: auto;
    padding:.5px .5px .5px .5px;
}

#foot {
    display:block;
    height:90px;
    border:solid black;
    border-width: 2px;
    margin-top:auto;
}

http://codepen.io/Kennpow/pen/bpJRvw

【问题讨论】:

标签: jquery html css


【解决方案1】:

margin-top:automargin-bottom:automargin-left:automargin-right:auto 相比的工作方式与您认为的不同。

margin-top:automargin-bottom:auto 将被计算为 0,而 margin-left:automargin-right:auto 将被计算为相等的边距。我认为这与浏览器如何呈现页面有关。

来自https://www.w3.org/TR/CSS2/visudet.html#normal-block

如果 'margin-top' 或 'margin-bottom' 为 'auto',则它们的使用值为 0。

来自https://www.w3.org/TR/CSS2/visudet.html#blockwidth

如果'margin-left'和'margin-right'都是'auto',它们使用的值 是平等的。

【讨论】:

    【解决方案2】:

    改变这个:

    #container: { display:flex; }
    

    编辑/添加:

    在 `#container' 周围添加另一个包装器并为其提供以下设置:

    #wrap_all {
      display:flex;
      height: 100vh;
    }
    

    (相同,已编辑)codepen:http://codepen.io/anon/pen/GZLvpj

    【讨论】:

    • 这很有效,狐狸在盒子里居中。谢谢!现在我需要将整个内容集中在网页中。
    • @KennyPower 请查看我更新的答案和更新的 codepen。
    猜你喜欢
    • 1970-01-01
    • 2010-09-22
    • 2013-03-01
    • 1970-01-01
    • 2016-06-23
    • 2014-02-25
    • 1970-01-01
    • 2015-06-10
    相关资源
    最近更新 更多