css多元素高度100%

时间:2013-01-31 23:18:04

标签: html css height

必须有十几个具有类似标题的帖子,但我发现没有一个能够有效地做我认为简单的事情,允许多个元素的高度为100%。请使用以下代码:

<html>
<head>
<style>
html, body, [role="main"] {height:100%; width:6in; overflow:hidden;}
[role="banner"] {position:fixed; top:0; left:0;}
.height {height:100%; width:100%}
</style>
</head>
<body>
<header role="banner">
<nav>
<a href="#1">Section one</a>
<a href="#2">Section two</a>
<a href="#3">Section three</a>
</nav>
</header>

<div role="main">

<section id="1" class="height">
</section>

<section id="2" class="height">
<header>
<h1>section title</h1>
</header>
<button>Navigate Articles</button>

<article class="height">
<h1>title</h1>
<p>paragraph</p>
</article>

<article class="height">
<h1>title</h1>
<p>paragraph</p>
</article>

</section>

<section id="3" class="height">
</section>

</div>

</body>
</html>

我希望能够在不滚动的情况下导航。单击链接将您带到某个部分,该部分将填充100%的屏幕高度。 当我使用上面的代码时,我没有得到我想要的效果。我使用类“高度”的元素使用固定位置在一点上接近。它适用于第一部分,但第二部分中的下部和文章将重叠。

2 个答案:

答案 0 :(得分:0)

实现您单独使用CSS所要求的功能并不实用。由于您指的是显示和隐藏内容,因此在点击导航链接时,您可能需要实施少量javascript来绑定点击操作以隐藏/显示功能。

我在您的代码中应用了以下内容:

<强> jQuery的:

//Hide all .height sections at first.
$('section.height').hide();

//Show them, when their respective link is clicked.
$('nav a').click(function() {
    var $this = $(this);
        section = $this.attr('href');

    $(section).siblings('.height').hide();
    $(section).show();    
});

并更新了您的CSS;

html, body, [role="main"] { 
    height:100%;
    overflow:hidden;
}
body {
    position: relative; /*so .height is relative to body when absolutely positioned*/
}

[role="banner"] {
    background: yellow;
    position:fixed;
    top:0;
    left:0;
    z-index: 999;
}

.height {
    background: red;
    height:100%;
    width:100%;
    position: absolute;
}
h1 {
    margin-top: 30px; /* to prevent menu overlap. */
}

您可以在此处查看结果:http://jsfiddle.net/mUEYM/2/

基本前提是将.height元素设置为position: absolute;。这将允许他们扩展到浏览器窗口的确切高度/宽度,前提是htmlbody也具有100%宽度&amp;高度。

我在导航中应用了z-index值,以确保它们在显示时位于.height个部分之上。

答案 1 :(得分:0)

好的,我终于让它与纯CSS一起工作了。问题不是从一个部分移动到另一个部分,而是控制子元素。

.parent { height: 100%; position: relative; overflow-y: hidden }

.child { min-height: 100%; }

有关说明,请参阅此Soure

相关问题