dann
dann

Reputation: 853

CSS div height percentage with margin percentage

I have a relative div with percentage height and margin.

<div class="a">
    <div class="b"></div>
</div>

.a{
    position:fixed;
    top:0;
    left:0;
    bottom:0;
    right:0;
}

.b{
    position:relative;
    background-color:red;
    height:75%;
    width:92%;
    margin: 25% 4% 0 4%;
}

Height 75% and margin-top 25% should add up to 100%. But, it is not cover all the height of the parent.

This is what I want:
enter image description here
This is what I get:
enter image description here

see fiddle : http://jsfiddle.net/hc3L7ynf/2/

Upvotes: 1

Views: 1201

Answers (3)

Persijn
Persijn

Reputation: 14990

Position Tricky

Changing your fixed position to absolute makes it easier to show what the problem is:

.a{
    position: absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
    border: 1px solid black;
}

.b{
    position: relative;
    background-color:red;
    height:75%;
    width:92%;
    margin: 25% 4% 0% 4%;
}
<div class="a">
    <div class="b"></div>
</div>

The easiest fix is just adding a class above it with height: 25%; or using a the ::before would do the same thing.

.a {
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  border: 1px solid black;
}
.b {
  position: relative;
  background-color: red;
  height: 75%;
}
.c {
  height: 25%;
}
<div class="a">
  <div class="c"></div>
  <div class="b"></div>
</div>

Upvotes: 1

Martijn van der Jagt
Martijn van der Jagt

Reputation: 524

Thanks for the fiddle example. What you want can be created with

.b {
    position:relative;
    background-color:red;
    height:96%;
    width:92%;
    margin: 4% 4% 0% 4%;
}

Upvotes: 0

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13988

Instead of margin using padding.

.b{
position:relative;
background-color:red;
height:75%;
width:92%;
padding: 25% 4% 0 4%;
}

DEMO

Upvotes: 0

Related Questions