简体   繁体   中英

Why doesn't percentage height work with display: table-cell?

I'm trying to center both horizontally and vertically a div inside an outer div. It works when the outer div has specific width and height set in pixels like

#countdownBox {
    width: 700px;
    height: 500px;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

but it fails when the height and width are percentages like

#countdownBox {
    width: 100%;
    height: 100%;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

Why is this and is there a work around?

EDIT Here is the HTML with container CSS:

#countdownBoxContainer {
width: 100%;
height: 100%;
position: absolute;
bottom: 0;
left: 0;
z-index: 3;
}

<div id="countdownBoxContainer">
    <div id="countdownBox">
      <div>
        hi there
      </div>
    </div>
 </div>

Based on the fact that you have width and height of 100% declared I'm going to assume that you're not expecting anyone to have to scroll here. See this Fiddle where I have a working solution based on those parameters.

Remember that display: table-cell; acts exactly like <td> elements and they won't render correctly unless they're in a <table> (or a container that is display: table; ).

The other problem is that <html> and <body> aren't necessarily the height of the screen if the content is very small. html, body { height: 100%; } html, body { height: 100%; } fixes this but it's a bit hacky.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM