如何在具有动态高度的固定div标题之后设置div内容的样式

时间:2012-07-01 22:34:18

标签: css html position fixed

以下情况:

<body>
 <div style="position:fixed; width:100%">[place holder for header]</div>
 <div style="position:relative;width:100%;margin-top:100px">[content]</div>
</body>

我需要标题始终可见且位于顶部,因此这个标题应该位于:fixed。 自我调整标题 - 高度后出现问题。如果标题高于100px,则隐藏部分内容。

我如何(CSS)动态设置关于标题末尾的内容div的开始位置。

2 个答案:

答案 0 :(得分:8)

我仍然在寻找一个仅限CSS的解决方案,但目前只使用一行JavaScript的想法 - 当使用jQuery时:

<强>的JavaScript

$(document).ready(function () {
    $('#content').css('marginTop', $('#header').outerHeight(true) );
});

<强> HTML

<body>
    <div id="header" style="[…]">[place holder for header]</div>
    <div id="content" style="[…]">[content]</div>
</body>

使用.outerHeight(true)的好处是,它会处理您可能已应用于标题的边框和边距。

答案 1 :(得分:6)

仅CSS解决方案(虽然不是超级干净)可能是两次显示相同的块:第一个块“position:fixed”,第二个块“visibility:hidden”。由于两者的高度相同,因此第二个块的作用是将页面内容下推到适当的级别。