Div height 100% and expands to fit content

后端 未结 15 803
攒了一身酷
攒了一身酷 2020-11-29 15:51

I have a div element on my page with its height set to 100%. The height of the body is also set to 100%. The inner div has a background and all that and is different from t

相关标签:
15条回答
  • 2020-11-29 16:09

    If you just leave the height: 100% and use display:block; the div will take as much space as the content inside the div. This way all the text will stay in the black background.

    0 讨论(0)
  • 2020-11-29 16:11

    This question may be old, but it deserves an update. Here is another way to do that:

    #yourdiv {
        display: flex;
        width:100%;
        height:100%;
    }
    
    0 讨论(0)
  • 2020-11-29 16:11

    Modern browsers support the "viewport height" unit. This will expand the div to the available viewport height. I find it more reliable than any other approach.

    #some_div {
        height: 100vh;
        background: black;
    }
    
    0 讨论(0)
  • 2020-11-29 16:14

    Try this:

    body { 
        min-height:100%; 
        background:red; 
    } 
    
    #some_div {
        min-height:100%; 
        background:black; 
    } 
    

    IE6 and earlier versions do not support the min-height property.

    I think the problem is that when you tell the body to have a height of 100%, it's background can only be as tall as the hieght of one browser "viewport" (the viewing area that excludes the browsers toolbars & statusbars & menubars and the window edges). If the content is taller than one viewport, it will overflow the height devoted to the background.

    This min-height property on the body should FORCE the background to be at least as tall as one viewport if your content does not fill one whole page down to the bottom, yet it should also let it grow downwards to encompass more interior content.

    0 讨论(0)
  • 2020-11-29 16:15

    Here is what you should do in the CSS style, on the main div

    display: block;
    overflow: auto;
    

    And do not touch height

    0 讨论(0)
  • 2020-11-29 16:15

    OVERLAY WITHOUT POSITION:FIXED

    A really cool way I've figured this out for a recent menu was setting the body to:

    position: relative
    

    and set your wrapper class like this:

    #overlaywrapper {
        position: absolute;
        top: 0;
        width: 100%;
        height: 100%;
        background: #00000080;
        z-index: 100;
    }
    

    This means that you don't have to set position fixed and can still allow for scrolling. I've used this for overlaying menu's that are REALLY big.

    0 讨论(0)
提交回复
热议问题