user1505713
user1505713

Reputation: 607

CSS: Percentage height computed as zero. Why?

JSFiddle

I have the following markup:

<body>
    <div class="slide">
        <header>
            <p id="progress">3/20
            </p>
            <!-- hfill -->
            <p id="timer">20:00
            </p>
        </header>
        <div class="question">
            <p id="question">What is 2+2?
            </p>

...and CSS:

img {
    display: block;
}        

.slide {
    border: 3px solid black;
    margin: 5% 10%;
    width: 80%;
    height: 100%;
}

header {
    margin: 0;
    height: 10%;
}

header p {
    margin: 0;
    font-size: 300%;
}        

#progress {
    float: left;
}

#timer {
    float: right;
} 

When I use Google's dev-tools, div.slide has dimensions 1074 x 208 px and header has 1068 x 0 px. Why is the header's height computed as zero? I'd like it to be 10% of its parent.

Upvotes: 0

Views: 2004

Answers (5)

Antonis Grigoriadis
Antonis Grigoriadis

Reputation: 2080

This is float collapse. If floated elements have non-floated parent elements, the parent will collapse and will appear to have height = 0.

You can use 3 solutions to solve that problem:

  1. Float the parent.
  2. Set height to the parent (eg 100px)
  3. Set parent overflow:auto

Upvotes: 0

Rajesh
Rajesh

Reputation: 1469

Its not a good idea to use height in percentages. Try reading Percentage Height HTML 5/CSS and Height in percent when parent has min-height and no height

To use the height in percentages,

  1. You need to have a height of the parent element.
  2. If you see your slide div, it is just beneath the body. So It did not work.
  3. Body does not have any height, so your height is computed to zero.

Upvotes: 0

j08691
j08691

Reputation: 207861

Because when you float header's content elements they're removed from the flow of the document and header collapses because it essentially has no content.

Add overflow:auto to your header's CSS rules and you'll get a height restored.

jsFiddle example

Upvotes: 0

Softwarehuset
Softwarehuset

Reputation: 815

Since your child elements all is set to floating, the element is rendered as "empty".

Upvotes: 0

brouxhaha
brouxhaha

Reputation: 4093

You need to clear your floats. By floating both elements inside header, it collapses into itself.

Add the following, which is the standard clearfix:

header:after {
    display: table;
    clear: both;
    content: '';
}

Demo

Upvotes: 2

Related Questions