Linda Keating
Linda Keating

Reputation: 2435

Why the percentage height doesn't work in my CSS?

I know this has been asked many times, but I'm stuck trying to get % height of an element to work. My understanding is the if the parent element has a height specified then setting a % height on the child element should work. Unfortunately I have tried to get this to work but I must be missing something.

body{
  border-radius: 10;
  height: 100%;
  position: relative;
}

.child-element{
   height: 50%;
   margin: none;
   background-color: gray;
 }

Where I have:

<body>
  <div class="child-element">
  </div>
</body>

Upvotes: 2

Views: 83

Answers (2)

Mark Rabjohn
Mark Rabjohn

Reputation: 1713

If the intention is to present the available browser client area as containing a single content rectangle (rather than having a tall one that scrolls), I prefer to do:

body {
top: 0; left: 0; right: 0; bottom: 0;
overflow: hidden; position: overflow;
}

If the aim is to have a child panel that builds height from nothing, then you need to be aware that the height of objects is based on width of parent, not height when the object is not absolute or fixed position. It's possible to build a square as follows:

.square {
 width: 20em;
    background: cyan;
}
.square:before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    padding-top: 100%;
    float: left;
}
.square:after {
    content: '';
    display: block;
    clear: both;
}
}
<div class="square">Square</div>

You can change the aspect ratio of the block by changing the amount of padding.

Hope this helps.

Mark

Upvotes: 0

Stickers
Stickers

Reputation: 78686

There is a parent element html for body tag also needs the height to be set.

html {
    height: 100%;
}

Simplified demo below (removed unnecessary rules and reset default body margin too).

html, body {
    height: 100%;
}
body {
    margin: 0;
}
.child-element {
    height: 50%;
    background-color: gray;
}
<body>
    <div class="child-element"></div>
</body>

Upvotes: 4

Related Questions