【问题标题】:why negative margin-bottom make the columns equal height?为什么负边距底部使列等高?
【发布时间】:2016-06-07 21:52:48
【问题描述】:

下面的css可以让三列都等高,我想知道为什么?

<html>
<style>
body,p{
        margin:0;
        padding:0;
    }
    #wrap{
        overflow:hidden;
        width:1200px;
        margin:0 auto;
    }
    #left,#center,#right {
        margin-bottom:-200px;
    }
    #left {
        float:left;
        width:300px;
        background:#777;
    }
    #center {
        float:left;
        width:300px;
        background:red;
    }
    #right {
        float:left;
        width:300px;
        background:green;
    }
    p {color:#FFF;text-align:center}
</style>
<body>
 <div id="wrap">
        <div id="left">
            <p style="height:250px">style="height:250px"</p>
        </div>
        <div id="center">
            <p style="height:300px">style="height:300px"</p>
        </div>
        <div id="right">
            <p style="height:400px">style="height:400px"</p>
        </div>
    </div>
</body>
</html>

所有列的高度均为 200 像素。

为什么显示的效果不是这个?

因为 200=400-200 ,100=300-200,50=250-200??

margin-bottom:-200px; 在这里是什么意思?
请画图详细说明原理。

【问题讨论】:

  • 负边距底部的效果会向上移动以下静态元素。你想要得到的可以用负边距顶部来完成
  • 为什么三个列的高度不是 200=400-200 ,100=300-200,50=250-200?负边距底部会向上移动以下静态元素,向上移动是否意味着这里的负数?
  • 因为您在 #wrap div 上分配了一个隐藏的溢出,并且您将负边距放在 div 标签的高度而不是 p 标签上。
  • 请务必标记正确答案。
  • 为什么下面的静态元素上移会产生效果?

标签: html css


【解决方案1】:

因为您在 #wrap div 上分配了一个隐藏的溢出,并且您将负边距放在 div 标签的高度而不是 p 标签上。 这是codepen上的示例。 codepen.io/elelowwaydi/pen/grYgYa?editors=1100。

【讨论】:

    【解决方案2】:

    这是因为 css 中的“wrap”类。 我做了一个 jsfiddle here。 我唯一改变的是删除溢出元素。 HTML(未更改):

     <body>
     <div id="wrap">
            <div id="left">
                <p style="height:250px">style="height:250px"</p>
            </div>
            <div id="center">
                <p style="height:300px">style="height:300px"</p>
            </div>
            <div id="right">
                <p style="height:400px">style="height:400px"</p>
            </div>
        </div>
    </body>
    

    CSS:

    body,p{
        margin:0;
        padding:0;
    }
    #wrap{
    
        width:1200px;
        margin:0 auto;
    }
    #left,#center,#right {
        margin-bottom:-200px;
    }
    #left {
        float:left;
        width:300px;
        background:#777;
    }
    #center {
        float:left;
        width:300px;
        background:red;
    }
    #right {
        float:left;
        width:300px;
        background:green;
    }
    #right2 {
        float:left;
        width:300px;
        background:blue;
    }
    p {color:#FFF;text-align:center}
    

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 2010-12-22
      • 1970-01-01
      • 2017-02-17
      • 2019-08-05
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多