如何将元素的位置设置为固定位置元素下方5px

时间:2013-10-01 12:23:28

标签: javascript css html

Ex:第一部:

<div style='position: fixed; width=100%'> ....</div>

现在我想将另一个Div 5px放在前一个Div的正下方。所以我做了

<div style='padding-top:5px; width=100%'> ....</div>

但它没有用,似乎padding-top将自己与窗口的顶部进行比较,而不是与之前的Div相比。如果我删除第一个div中的position: fixed;那么它会没问题,但我不希望这样。

我希望第一个Div得到固定位置&amp;第二个Div的位置比第一个位置低5px。那怎么办?

5 个答案:

答案 0 :(得分:3)

position: fixed从常规流中删除元素。你不能再使用流量定位了。

可能有正确的方法来做你想做的事,但我不知道你想要什么,因为你告诉了我们Y,而不是X:https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem


我想我明白你想要什么。如果你总是知道标题的高度,你可以添加一个偏移量,填充和边距应该都有效。

<div id="header" style="position: fixed; top: 0; width: 100%; height: 20px;">
<div id="content" style="margin-top: 20px;">Content goes here</div>

如果标题可以更改高度,请调整CSS,使标题和内容分别更改其高度和内容。

<div id="container" class="adjustheaderheight">
    <div id="header">
    <div id="content">Content goes here</div>
</div>

#header { position: fixed; top: 0; width: 100%; height: 20px; }
#content { margin-top: 20px; }
#container.adjustheaderheight #header {
    height: 40px;
}
#container.adjustheaderheight #content {
    margin-top: 40px;
}

如果您的标题动态更改高度,则需要动态更改内容偏移量,但我强烈建议您不要使用动态标题。

答案 1 :(得分:0)

将两个div放在固定的包装中。你也有无效的css语法width = 100%必须是宽度:100%。

<div style="position: fixed;">
   <div style=' width:100%'> ....</div>
   <div style='margin-top:5px; width:100%'> ....</div>
</div>

然而,这使得2个div被修复了......这可能不是你想要的。您可以执行以下操作:

    <div style='position: fixed; width:100%'> ....</div>
   <div style='position:absolute; width:300px;height:200px;top:300px;left:300px'> ....</div>

css值只是例如......

  

更新:

这是你想要的吗? http://jsfiddle.net/kasperfish/K8N4f/1/

<div id="fixed">fixed</div>
<div id="widget" >content <br>hjgjhgjhgjhgh</div>

#fixed{
    width:100%;
    position:fixed;
    background:yellow;
    height:50px;
    z-index:2;
}
#widget{

    background:blue;
    position: absolute;
    top:55px;
    margin-top:15px;
    width:100%
}

答案 2 :(得分:0)

您是否尝试过margin-top? margin-top: 5px

答案 3 :(得分:0)

您可能希望将这两个分区包含在另一个分区中,并使这个新的外部分区位置固定。像这样---&gt;

<div style='position: fixed; width=100%'>
  <div style='width=100%'> ....</div>
  <div style='padding-top:5px; width=100%'> ....</div>
</div>

答案 4 :(得分:0)

如果您已经尝试过边距并且无法使用填充,只要您在div中没有​​背景颜色或图像,那么您将无法区分这两种方式之间的区别这样做。