我正在构建一个具有动态高度的布局(正如大多数人所做的那样).我一直在寻找一段时间,但没有找到与我相似的案例.所以在这里,我的简化代码:
HTML:
<div id="body"><div id="content">
content
</div>
</div>
<div id="footer">
abc
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
#footer{
position: absolute;
bottom: 0;
width: 100%;
background: #ddd;
}
#body{
padding: 60px 50px 70px 50px;
position: relative;
min-height: calc(100% - 130px);
}
#content{
font-family: verdana;
margin-left: 200px;
border-left: 5px solid #ddd;
padding: 0 0 0 10px;
min-height: 100%;
min-width: 500px;
}
body{
margin:0;
overflow-y:scroll;
height:100%;
position:relative;
}
html{
height:100%;
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我使用该代码时,内容高度计算不正确,结果看起来像这个小提琴,而我正在尝试做的是当内容很短时,它应该看起来像这样,当内容很长时,它看起来应该是这样的.
如果我改变min-height到height,当内容很短,我得到了我想要的,但如果内容很长,我得到这个恼人的布局
它似乎calc无法在未指定(使用min-height)时读取高度属性,但如果height指定了,那么我无法获得动态高度,有没有其他解决方案来实现这一点?
PS:我正在尝试做的是#content根据页面高度的最小高度来制作延伸边框
注意:
另一个奇怪的事实是,实际上我目前的代码正在研究最新的chrome和IE,但在最新的firefox和opera上有这个问题.我试图使用jsfiddle重现问题,并且令我敬畏的是,所有的浏览器都有相同的问题,我已经将所有相关的html和css(复制生成的html和css)包含到jsfiddle只是为了找到我的代码是根本不工作,我很困惑
为什么不使用弹性盒子?听起来你想要一个粘性页脚- 也就是说,当内容不是很高时,页脚位于视口的底部,但当内容超过视口高度时,它位于内容的底部。这与圣杯的设计非常相似。这是一个不使用 JavaScript 的 HTML5+CSS3 解决方案:
* {
/* personal preference */
margin: 0;
padding: 0;
}
html {
/* make sure we use up the whole viewport */
width: 100%;
height: 100%;
/* for debugging, a red background lets us see any seams */
background-color: red;
}
body {
/* make the body a vertical flex container */
/* https://css-tricks.com/snippets/css/a-guide-to-flexbox/ */
display: flex;
flex-direction: column;
/* make sure we use the full width but allow for more height */
width: 100%;
min-height: 100%; /* this helps with the sticky footer */
}
main {
/* Allow the content to grow but not shrink */
flex-grow: 1;
flex-shrink 0;
/* for debugging, a blue background lets us see the content */
background-color: skyblue;
}
footer {
/* do not allow the footer to shrink */
flex-shrink: 0;
/* for debugging, a gray background lets us see the footer */
background-color: gray;
}Run Code Online (Sandbox Code Playgroud)
<main>
<p>This is the content. Resize the viewport vertically to see how the footer behaves.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
<p>This is the content.</p>
</main>
<footer>
<p>This is the footer. Resize the viewport horizontally to see how the height behaves when text wraps.</p>
<p>This is the footer.</p>
</footer>Run Code Online (Sandbox Code Playgroud)
如果您不想自己将代码复制到小提琴中,我已经为您完成了。如果您想支持较旧的浏览器,您可能需要使用一些供应商前缀- 在撰写本文时,弹性框相对较新。