【问题标题】:CSS child elements "margin-top" property affects parent element [duplicate]CSS子元素“margin-top”属性影响父元素[重复]
【发布时间】:2014-02-23 16:04:35
【问题描述】:

在带有文档类型 的 HTML 5 中,我有内部正文:

<div style="width:100%; background-color: #cccccc;">
    <div style="margin-top:20px; width:100px; background-color: #aa0000;">Sub</div>
    Main
</div>

http://jsfiddle.net/F3kXw/

当我在 Firefox 中渲染时,我得到的外部 div 距离页面顶部有 20px 的边距, 我只需要子 div 从外部 div 有 20px 的边距。如果我将字符放在子 div 的顶部,它会起作用:

<div style="width:100%; background-color: #cccccc;">
    Main
    <div style="margin-top:20px; width:100px; background-color: #aa0000;">Sub</div>
    Main
</div>

例如http://jsfiddle.net/F3kXw/2/

这对我来说毫无意义,我过去从未遇到过这个问题。

【问题讨论】:

标签: css html


【解决方案1】:

试试这个代码可能会有所帮助

<div class="website_sub_frame" style="width:100%; background-color: #cccccc;overflow:hidden">

    <div style="clear:both; margin-top:20px; width:100px; background-color: #aa0000;">Sub</div>
    Main
</div>

【讨论】:

    【解决方案2】:

    尝试将 margin-bottom 改为 margin-top 给子 div。就是这样。

    <div class="website_sub_frame" style="width:100%; background-color: #cccccc;">
        <div style="width:100px; background-color: #aa0000; margin-bottom:20px;">Sub</div>
        Main
    </div>
    

    这是一个有效的demo

    或者你正在寻找这个?

    <div class="website_sub_frame" style="width:100%; background-color: #cccccc;">
        Main
        <div style="width:100px; background-color: #aa0000; margin-top:20px;">Sub</div>
    </div>
    

    这是一个有效的demo

    希望对你有帮助!

    【讨论】:

      【解决方案3】:

      使父 DIV 浮动。不完全确定为什么会修复它,但它确实有效。

       <div style="float:left; width:100%; background-color: #cccccc;">
         <div style="margin-top:20px; width:100px; background-color: #aa0000;">Sub</div>
         Main
      </div>
      

      【讨论】:

        【解决方案4】:

        您为什么不在子 div 上方添加另一个 div 并将其高度设置为 20 像素,而不是使用顶部边距。 例如: div class="website_sub_frame" style="width:100%; 背景颜色: #cccccc;" div style="height:30px">子/div 主要的 /div

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-09-29
          • 2011-01-13
          • 2021-10-19
          • 2013-03-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多