问题
In my website, I am using two divs that should have their height
like in this picture.
So, there is a div
with height:90px;
that is aligned to the bottom of the window, now what can I do if I want the 2nd div (red) to "fill" the rest of the window? Red div
should have the height
of the window minus the height
of the blue div
but something like calc(100vh - 90px)
wouldn't work, right?
Thanks!
回答1:
Actually height: calc(100vh - 90px);
does work
html,
body {
min-height: 100%;
}
* {
margin: 0;
padding: 0;
}
footer {
height: 90px;
background: blue;
}
main {
background: red;
height: calc(100vh - 90px);
}
<main></main>
<footer></footer>
However, it's not entirely clear how you want this to react if the content would normally cause vertical scrolling. Then this is not the answer, probably.
Alternative solution with flex-box
html,
body {
min-height: 100%;
}
* {
margin: 0;
padding: 0;
}
.wrap {
display: flex;
flex-direction: column;
flex-wrap:no-wrap;
min-height:100vh;
}
main {
background: red;
flex:1;
}
footer {
flex-basis:90px;
flex-shrink:0;
background: rgba(0, 0, 255, 1);
}
<div class="wrap">
<main>
<div class="content"></div>
</main>
<footer>
</footer>
</div>
回答2:
I don't believe this can be done without using javascript to get the window height.
So, I'd use some javascript to get the window height, and then change the height of the top element accordingly (assuming a static footer).
HTML
<div class="top" id="top">
</div>
<div class="bottom">
</div>
CSS
.top{
background-color:red;
}
.bottom{
height: 90px;
background-color:blue;
}
Javascript
var h = window.innerHeight;
document.getElementById("top").style.height = (h - 90) + "px";
http://jsfiddle.net/n5aLt5y6/1/
回答3:
Assuming you cannot use calc
in your project; please consider using the following JavaScript in order set the height of your first div.
How does it work:
- Second DIV (footer) is positioned from the bottom using simply CSS
bottom:0;
- First DIV height is adjusted by JavaScript when window
load
orresize
.
https://jsbin.com/lunitafuja/1/edit?html,output
<style>
html, body {
margin: 0;
padding: 0;
}
#a {
top: 0;
position: absolute;
background-color: red;
width: 100vh;
}
#b {
position: absolute;
background-color: blue;
width: 100vh;
height: 100px;
bottom: 0;
}
</style>
<script>
window.app = {
start: function () {
var bTop = Math.round(document.getElementById('b').getBoundingClientRect().top);
var a = document.getElementById('a').style.height = bTop + 'px';
}
};
</script>
来源:https://stackoverflow.com/questions/31268717/css-div-height-calculation-without-calc