Firefox ignoring min-height in CSS

2019-03-03 07:44发布

问题:

For some reason, min-height is not working on Firefox. I tried setting min-height on the body, but Firefox totally ignored it. Since my page is dynamic, I cannot just set the height to 100%. What should I do?

body {
border: 1px solid black;
width: 100%;
min-height: 100%;
}
<body>

This is the body.

</body>

回答1:

height percentages are inherited (that includes min-height and max-height, too). From the CSS spec:

Specifies a percentage for determining the used value. The percentage is calculated with respect to the height of the generated box's containing block.

What most people don't realize is that body is just an element like any other, and so is html. What people also don't realize is that these elements don't have an inherent height set. The parent of html is the viewport, and it does have an inherent height of 100%. The viewport is--more or less--the browser window, minus any menu or title bars.

Since height percentages inherit from their parent, and you don't have a height set for your html element, your CSS of min-height: 100%; doesn't have a value to take 100% of. So your body is taking min-height: 100% of 0, basically.

To fix this, simply tell your html element to be 100% the height of the viewport:

html {
    height: 100%; /* this is the important bit */
}

body {
    border: 1px solid black;
    width: 100%;
    min-height: 100%;
    margin: 1px; /* I added this to make the border around the body a little easier to see. Normally you want to set it to 0 or leave it alone completely */
}
<body>
This is the body.
</body>

However, if you don't want to set your entire document to be as tall as the viewport (I strongly recommend that you do), you can also use position: absolute; on your body element so that the percentage height will always resolve, regardless of the height of its parent element. This is what Saqib was trying to get at in the comments above. From the CSS Spec on min-height and height, respectively:

If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').

-

Note that the height of the containing block of an absolutely positioned element is independent of the size of the element itself, and thus a percentage height on such an element can always be resolved.

body {
    border: 1px solid black;
    width: 100%;
    min-height: 100%;
    position: absolute;
    margin: 1px; /* I added this to make the border around the body a little easier to see. Normally you want to set it to 0 or leave it alone completely */
}
<body>
This is the body.
</body>

(I don't know what code of yours is working in Chrome, but the code in your question has the same behavior in Chrome as it does in Firefox.)