【问题标题】:3divs with internal margin具有内部边距的 3div
【发布时间】:2013-07-16 20:24:37
【问题描述】:

我想要三个带有内部边距(没有填充)的 div,如下所示:

+---------------------+
|         15px        |
| +-----------------+ |
| |       20px      | |
| | +-------------+ | |
| | |             | | |
| | |             | | |
| | |             | | |
| | |             | | |
| | +-------------+ | |
| +-----------------+ |
+---------------------+

我对三个 div 使用了以下样式:

#outer{
 width: 800px;
 height: 800px;
 position: absolute;
}
#middle{
  width: 750px;
  height: 750px;
  position: relative;
  margin-top: 15px;
}
#inner{
  width: 700px;
  height: 700px;
  margin-top: 20px;
}

通过上述样式,不包括内部 div,margin 效果很好并且位置正确。但是如果我放置内部 div,那么 margin-top 就变成了最内部 div 的边距,如下所示:

+---------------------+
|         20px        |
| +-----------------+ |
| | +-------------+ | |
| | |             | |
| | |             | | |
| | |             | | |
| | |             | | |
| | |             | | |
| | +-------------+ | |
| +-----------------+ |
+---------------------+

即,中间 div 的 margin-top 也从 15px 增加到 20px(这实际上是内部 div 的 margin-top),即使我给出 position: relative to inner div。 我可以通过对中间 div 应用填充(padding-top:20px)来实现所需的边距。但我想在没有填充的情况下完成这些边距。 所以如果我想为 3、4 甚至更多的 div 做这种类型的边距,怎么做? 任何帮助将不胜感激?

【问题讨论】:

    标签: html margin


    【解决方案1】:

    请看看这个小提琴http://jsfiddle.net/JzUCm/,这是你想要的吗?

    我已将 css 更新为:

    #outer{
     width: 800px;
     height: 800px;
     position: absolute;
        background:yellow;
    }
    #middle{
      width: 750px;
      height: 750px;
      position: relative;
      margin: 15px 25px 0px 25px;
        background:red;
    }
    #inner{
      width: 700px;
      height: 700px;
      top: 20px;
      left:25px;
      position:absolute;
      background:green;
    }
    

    基本上我使第三个 div 相对于父级(中间 div)绝对定位。也忽略背景颜色,只添加它们以便您可以看到发生了什么。

    【讨论】:

    • 如果我在内部 div 中创建第 4 个 div,那么第 4 个 div 的位置将再次是相对的,对吧?
    猜你喜欢
    • 2010-11-17
    • 2011-04-27
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多