yuvi
yuvi

Reputation: 18427

css height is wrong when using percentage

I'm trying to build a generic alert element, that changes according to the parent div's height. At first, when I just designed everything, I used specific heights, but now I want to make it all relative, and for some reason those are calculated wrong!

so say this is my html:

<div class="alert">
    <span class="divider-vertical"></span>
</div>

and my css used to be:

.alert {
    height: 80px;
} 

.divider-vertical {
    height: 30px;
    margin: 25px 0; // 25*2 + 30 = 80
}

Now I wanted to turn this into relative percentages, so:

<div style="height: 80px;">
  <div class="alert">
    <span class="divider-vertical"></span>
  </div>
</div>

and my css:

.alert {
    height: 100%;
}

.divider-vertical {
    height: 37.5%;
    margin: 25px 0;
}

I used that figure based on the calculation: 100 * (30.0 / 80.0) = 37.5. Now when I opened up chrome and checked to see the computed attributes, I found that .alert has a height of 80px (as it should), but .divider-vertical has only 29.25px. Why is that?

There's no other conflicting attribute somewhere else and the chrome dev tools assure me that the elements height is indeed 37.5%. Notice this isn't a case of some infinite decimal number, the calculation returns exactly 37.5% so why would there be any trouble here?

Upvotes: 1

Views: 1054

Answers (2)

Paulie_D
Paulie_D

Reputation: 114991

I would assume that the box-sizing: border-box property is set in your CSS to account for borders/padding etc thus causing some confusion?

That being the case you probably want to keep it so that everything is consistent.

Upvotes: 2

vals
vals

Reputation: 64164

I you wnat to be able to set dimensions to your element, you should make it of the block family

for instance

.divider-vertical {
    display: inline-block;
}

will solve your issue

Upvotes: 2

Related Questions