CSS 100% height layout

2019-01-07 09:40发布

问题:

I know this is a sort of a common problem, and I looked up some solutions, but couldn't find exactly what I was looking for.

I would like to convert this to a tableless layout.

Note: header and footer have to be set to a fixed height in pixels (50px is ok).

The main problem I'm having is that I cannot get that "big box" in the middle to behave like it does when it's done with tables. There are solutions which work OK for a variable length content (text, images), but I would like this box look and behave like a box - with borders, rounded corners and all.

回答1:

You can do it with table style CSS properties, but still retain table less markup (which is still a win).

Example

HTML

<div id="container">
    <div id="header"><div>header</div></div>
    <div id="content"><div>content</div></div>
    <div id="footer"><div>footer</div></div>
</div>

CSS

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

#container {
    display: table; 
    width: 100%;
    height: 100%;
    border: 1px solid red;   
    text-align: center;
}

#container > div {   
    display: table-row;   
    width: 100%;
}

#container > div > div {   
    display: table-cell;   
    width: 100%;
    border-radius:10px; 

}

#header > div {
    height:50px; 
    border:solid 2px #aaa;
}

#content > div {
    height: 100%;    
    background:#f0f4f0; 
    border:solid 2px #5a5;
}

#footer > div {
    height:50px; 
    border:solid 2px #a55;
}

jsFiddle.



回答2:

'Multiple absolute co-ordinates' is a nice way to achieve this. This is when you absolutely position a box, then give it both top and bottom co-ordinates. Without specifying a height, you get a box which wants to be 10px from the top, and 10px from the bottom edges of its parent.

Here's an example

There is an IE6 specific style you'll need to add, if you care about that browser.

Here's an article on the technique (plus the IE6 fix) - it's a good one to know, even if you don't use it for this problem.



回答3:

You haven't said anything about heights of your sub elements, so I have had to make some presumptions. You could use percentages if you wanted.

<style>
html,body {margin:0;padding:0;
}
#mainContainer {
height:100%;
width:100%;
}

#header {
height:15%;
width:100%;
background-color:red;
}

#center {
height:75%;
width:100%;
background-color:blue;
}

#footer {
height:10%;
width:100%;
background-color:pink;
}
</style>

    <body>
    <div id="mainContainer">
    <div id="header">Header</div>
    <div id="center">Center</div>
    <div id="footer">Footer</div>

</div>

    </div>
    </body>