【问题标题】:Content after relative placed div相对放置的 div 后的内容
【发布时间】:2014-10-21 17:47:06
【问题描述】:

如果我相对显示一个 div 并给它一个上边距,我是否必须给以下所有内容同样的上边距?因为后面的内容将在元素的常规位置之后。

http://jsfiddle.net/u9cgu6er/

正如您在此处看到的,blue div 位于 red 上方,紧随蓝色的原始位置。

有没有办法让red 降低 20 像素而不使其成为relative?换句话说,不要对以下所有内容都这样做。

#a {
  width:100%;
  background-color:yellow;
  height:50px;
}
#b {
  position:relative;
  top:20px;
  width:50%;
  background-color:blue;
  height:50px;
}
#c {
  width:100%;
  background-color:red;
  height:50px;
}
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>

【问题讨论】:

  • 为什么不使用margin-top而不是定位元素?
  • 确实如此。 “top”不是边距——它相对于其在流中的自然位置的顶部移动元素。它之外的其他元素不会知道它的重新定位,但如果你只使用边距,那会很好。
  • 另外,您可能会发现这很有帮助:stackoverflow.com/questions/4036176/css-top-vs-margin-top

标签: html css


【解决方案1】:

margin-top: 20px; 添加到您的#c。 @HashemQolami 是对的,如果可以的话,在#b 上使用margin-top 而不是位置relative 会更容易维护你的css。

【讨论】:

  • 实际上我的意思是使用margin-top 代替#b 而不是top 偏移量。这是哈希姆顺便说一句:)
  • @HashemQolami,对不起,您的名字有错误!我已经更正了,真的很抱歉!!
【解决方案2】:

最简单的方法是将#bmargin-top 设置为20px,然后#c 将跟随它。

#a {
  width:100%;
  background-color:yellow;
  height:50px;
}
#b {
  margin-top:20px;
  width:50%;
  background-color:blue;
  height:50px;
}
#c {
  width:100%;
  background-color:red;
  height:50px;
}
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>

这样,它不会从文档流中删除#b

【讨论】:

    【解决方案3】:

    您可以将margin-bottom: 40px; 添加到#b 元素:

    #a {
        width:100%;
        background-color:yellow;
        height:50px;
    }
    #b {
        position:relative;
        top:20px;
        width:50%;
        background-color:blue;
        height:50px;
        margin-bottom: 40px;
    }
    #c {
        width:100%;
        background-color:red;
        height:50px;
    }
    <div id="a"></div>
    <div id="b"></div>
    <div id="c"></div>

    margin-top: 40px;#c 元素:

    #a {
        width:100%;
        background-color:yellow;
        height:50px;
    }
    #b {
        position:relative;
        top:20px;
        width:50%;
        background-color:blue;
        height:50px;
        
    }
    #c {
        width:100%;
        background-color:red;
        height:50px;
        margin-top: 40px;
    }
    <div id="a"></div>
    <div id="b"></div>
    <div id="c"></div>

    两者都行。

    【讨论】:

      【解决方案4】:

      在#c的顶部添加40px的边距

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多