Set div to fill in the rest of the height dynamica

2019-03-14 02:17发布

问题:

So. My code is something along the lines of

<html>
<body>
    <div id="header" style="width:100%;min-height:0;display:block;background-color:#000">
        <img src="header_image.svg" />
    </div>
    <div id="content" style"display:block">
        Some content
    </div>
</body>
</html>

I have an svg in the header that I have set so that it matches the width of the window and the height scales to preserve the svg. Then I have the rest of the page in another div. I would like it so that the page doesn't scroll and this content div fills to fit the rest of the window. The problem is that since the height of the header changes with the width of the window, I can't set the content div in pixels or percentage or anything concrete.

How can I set the height of the content div to change dynamically with the height of the header?

I don't know Javascript or JQuery (I know, I know - I should), but ideally the height of the content div would be set to be something like height:(height of viewport)-(height of header), but I haven't a clue how to do this.

回答1:

you don't have to use a script for that. and also: I recommend you to separate your styling from your markup.

HTML

<div id="wrapper">
    <div id="header">
        <img src="header_image.svg" alt="the img is empty"/>
    </div>
    <div id="content">Some content</div>
</div>

add this to your CSS

html, body {
    height: 100%;
    margin: 0px;
}

/* this is the big trick*/
#wrapper:before {
    content:'';
    float: left;
    height: 100%;
}
#wrapper {
    height: 100%;
    background-color: black;
    color: white;
}
#header {
    background-color:#000;
}
#content {
    background-color: gray;
}
/* this is the big trick*/
#content:after {
    content:'';
    display: block;
    clear: both;
}

Working Fiddle

Tested on: IE10, IE9, IE8, FF, Chrome.

  1. didn't use absolute positioning
  2. didn't use Script (Pure CSS solution)
  3. fluid layout
  4. cross-browser

Explanation: with pseudo element, I'm creating a floating element (without content or width, so he's invisible) that has 100% of the container height.

and with another pseudo element I'm creating a div just after the content div. (also without content, so he's also invisible) that has the clear attribute. so he has to be below the floated one I've created earlier. making the content to go all the way down.